繁体   English   中英

如何自动为文本文件中所有匹配的字符串编号?

[英]How to automatically number all the matching strings in a text file?

我有一个文本文件C:\\text\\sample.txt 如何搜索此文本文件,并给定字符串的所有实例编号( 使用正则表达式 ),例如,以“ h”开头并以“ y”结尾的单词?

sample.txt样子:(对于此示例文件,我使用的正则表达式为\\bh.+y\\b它将匹配happy和history。)

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())

我没有您的文本文件,所以我仅使用文本“当一个新的快乐时,您感到高兴吗,您感到多么高兴,非常高兴”为例,向您展示解决此问题的方法。

word_to_find = "happy"
text_to_count = "When a happy new Are you happy How happy very happy"
text_table = text_to_count.split(" ")
counter = 1
text_output = ""

for i in text_table:
  if i == word_to_find:
    text_output += str(counter) + ">"+ str(i) + " "
    counter += 1
  else:
    text_output += str(i) + " "

print(text_output)

这给你作为输出:

When a 1>happy new Are you 2>happy How 3>happy very 4>happy 

您应该只用文本文件替换变量text_to_count

如果要添加其他单词,可以将它们添加到word_to_find并调整if条件

据我了解您的问题,您需要在文件中搜索特定的模式,然后将该匹配项与到目前为止找到的匹配项总数一起放在前面。

这是一个使用re.sub和custom函数以及全局计数器的示例。 您可以将其合并到您的代码中:

>>> 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.'

您必须在( )包含正则表达式,以便捕获并返回匹配项,以便对其进行修改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM