获取字符串的行号

2024-06-17 05:09:44 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我从一个文件中提取了一个很长的字符串:

 lf = open(filename, 'r')
 text = lf.readlines()    
 lf.close()
   

lineList = [line.strip() for line in open(filename)]
text = '\n'.join(lineList)

如何在此字符串中找到特定正则表达式的行号(在本例中是“匹配”的行号):

 regex = re.compile(somepattern)
 for match in re.findall(regex, text):
      continue

提前感谢您的时间

编辑:忘记添加我们正在搜索的模式是多行的,我对起始行感兴趣


Tags: 文件字符串textinreforcloseline
2条回答

我们需要使用re.finditer获取re.Match对象,而不是字符串本身,这将允许获取有关起始位置的信息。考虑下面的例子:假设我想找到紧跟在新行之前和之后的每两个数字(^ {< CD3>}),然后:

import re
lineList = ["123","456","789","ABC","XYZ"]
text = '\n'.join(lineList)
for match in re.finditer(r"\d\n\d", text, re.MULTILINE):
    start = match.span()[0]  # .span() gives tuple (start, end)
    line_no = text[:start].count("\n")
    print(line_no)

输出:

0
1

说明:在我获得起始位置后,我只需计算该位置之前的换行数,这与获得行数相同。注意:我假设行号从0开始

也许是这样的:

lf = open(filename, 'r')
text_lines = lf.readlines()    
lf.close()

regex = re.compile(somepattern)
for line_number, line in enumerate(text_lines):
  for match in re.findall(regex, line):
    print('Match found on line %d: %s' % (line_number, match))

相关问题 更多 >