我如何才能不仅捕获匹配项,还捕获它出现的行号?
我有以下脚本:
re.findall(pattern, a_file.read(), re.MULTILINE)
注意:我有很多文件要解析,不想逐行读取(或重读)文件。
请您参考如下方法:
尝试遍历每一行(使用计数)以确定可以找到匹配项的行号。它可能看起来像这样:
with open('somefile.txt', 'r') as a_file:
linecount = 0
for line in a_file:
linecount += 1
result = re.findall(pattern, line)
...
