我有一个文本文件C:\text\sample.txt
。如何搜索此文本文件,并给定字符串的所有实例编号(使用正则表达式),例如,以“ h”开头和以“ y”结尾的单词?
什么sample.txt
模样:(对于此示例文件,我用正则表达式\bh.+y\b
,它会匹配快乐和历史。)
When a happy new history ...
Are you happy ...
How history ... very happy ...
...
我希望达到的编号效果:
When a 1>happy new 2>history ...
Are you 3>happy ...
How 4>history ... very 5>happy ...
...
我是python编程的新手。如何使用python代码实现此目标?
目前,我只想出以下代码:
import fileinput
import re
for line in fileinput.input('sample.txt',inplace=1):
line = re.sub(r'\bh.+y\b',r'\bh.+y\b', line.rstrip())
据我了解您的问题,您需要在文件中搜索特定的模式,然后将该匹配项与到目前为止找到的匹配项总数一起放在前面。
这是使用re.sub
和自定义函数以及全局计数器的示例。您可以将其合并到您的代码中:
>>> count = 1
>>> s
'The happy and hungry hippo had a happy meal for lunch.'
>>> def f(m):
... global count
... value = '{}-{}'.format(count, m.group())
... count = count + 1
... return value
...
>>> re.sub(r'(h\w+y)', f, s)
'The 1-happy and 2-hungry hippo had a 3-happy meal for lunch.'
您必须将正则表达式包含在其中,( )
以便捕获并返回匹配项,以便对其进行修改。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句