【发布时间】:2020-11-28 22:08:39
【问题描述】:
我正在尝试在文本文件中搜索并匹配两行上的部分(或全部)文本。 我需要返回匹配字符串(第一行)的行号(在文本文件中)。
一个示例文本文件可以是:
这是第一行的一些文字
这是更多或第二行
第三行有更多的文字。
如果我试图找到以下字符串“第二行第三行”,它将返回行号 2(如果第一行是 0,则返回真正的 1)。
我看过许多类似的例子,似乎我应该使用 re 包,但是我无法锻炼如何返回行号(Python - Find line number from text file、Python regex: Search across multilines、re.search Multiple lines Python
此代码跨多行查找字符串
import re
a = open('example.txt','r').read()
if re.findall('second line\nThis third line', a, re.MULTILINE):
print('found!')
下面的代码逐行循环读取文本文件。我意识到它不会为多行字符串找到匹配项,因为它一次读取一行。
with open('example.txt') as f:
for line_no, line in enumerate(f):
if line == 'second line\nThis third line':
print ('String found on line: ' + str(line_no))
break
else: # for loop ended => line not found
line_no = -1
print ('\nString Not found')
问题:如何在我的第一个示例中获取代码以返回文本文件的行号,或者将此代码放置为某种计算行数的循环?
【问题讨论】: