我有一个这样的文本文件:
john123:
1
2
coconut_rum.zip
bob234513253:
0
jackdaniels.zip
nowater.zip
3
judy88009:
dontdrink.zip
9
tommi54321:
dontdrinkalso.zip
92
...
我有数百万个这样的条目。在
我想取一个5位数长的名字和号码。我试过了:
^{pr2}$但至少有5个数字。在
^{3}$Q1:如何找到精确5位数字的名字?在
Q2:我想用5位数字附加与这些名称相关联的zip文件。如何使用正则表达式来实现这一点?在
这是因为
\w
包含数字字符:您需要更具体地告诉Python您只需要字母:
^{pr2}$关于您的第二个问题,您可以使用以下内容:
或者,没有所有的评论:
下面是一个演示:
但是请记住,一次读入文件的所有内容并不是很有效。相反,您应该考虑生成一个生成器函数,一次生成一个数据块。此外,还可以通过预编译正则表达式模式来提高性能。在
输出
^{pr2}$评论
我试图保持它非常简单,如果您的输入很长,那么您应该按照iCodez的建议,实现一个生成器,该生成器一次只能存储一条记录,而对于regexp匹配,我尝试了一点优化,只搜索头的最后7个字符。在
附录:记录生成器的简单实现
您需要将regex限制在单词的末尾,这样它就不会再使用
\b
匹配了请参见示例http://regex101.com/r/oC1yO6/1
正则表达式会匹配的
^{pr2}$python代码应该是
相关问题 更多 >
编程相关推荐