Skip to main content
 首页 » 编程设计

python之从文本文件中获取一定长度的所有数字的好方法

2025年05月04日35lautakyan007

我有一个文件,我想从中获取所有 6 位数字 (id),它们并不总是被空格包围,但它们不会触及其他数字(最大数字有 6 位)。文件中还有其他较小的无关数字。

我想出了这个解决方案,它按预期工作,但是我想知道是否有更优雅的方法

print [num for num in "".join([e if e in "0123456789, " else " " 
       for e in whole_file ]).split() if len(num) == 6] 

请您参考如下方法:

我会使用正则表达式进行匹配。

\D[\d]{6}\D 

将精确匹配 6 位数字

\D    will match non-digit (whatever you have that separates your numbers) 
\d    matches 0-9 
{6}   means 6 times