【问题标题】:Search a text file for a multi line string and return line number in Python在文本文件中搜索多行字符串并在 Python 中返回行号
【发布时间】:2020-11-28 22:08:39
【问题描述】:

我正在尝试在文本文件中搜索并匹配两行上的部分(或全部)文本。 我需要返回匹配字符串(第一行)的行号(在文本文件中)。

一个示例文本文件可以是:

这是第一行的一些文字
这是更多或第二行
第三行有更多的文字。

如果我试图找到以下字符串“第二行第三行”,它将返回行号 2(如果第一行是 0,则返回真正的 1)。

我看过许多类似的例子,似乎我应该使用 re 包,但是我无法锻炼如何返回行号(Python - Find line number from text filePython regex: Search across multilinesre.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')

问题:如何在我的第一个示例中获取代码以返回文本文件的行号,或者将此代码放置为某种计算行数的循环?

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    使用.count()match 对象计算匹配前的换行数:

    import re
    
    with open('example.txt', 'r') as file:
        content = file.read()
    match = re.search('second line\nThis third line', content)
    if match:
        print('Found a match starting on line', content.count('\n', 0, match.start()))
    

    match.start()content中匹配开始的位置。

    content.count('\n', 0, match.start()) 计算字符位置0 和匹配开始之间content 中的换行数。

    如果您希望行号从 1 而不是 0 开始,请使用 1 + content.count('\n', 0, match.start())

    【讨论】:

      【解决方案2】:

      这可能对你有用:

      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:
          count = 0
          line1 = 'second line\nThis third line'
          line1 = line1.split('\n')
          found = 0
          not_found = 0
          for line_no, line in enumerate(f):
              if line1[count] in line :
                  count += 1
                  if count == 1 :
                      found = line_no
                  if count == len(line1):
                      not_found = 1
                      print ('String found on line: ' + str(found))
              elif count > 0 :
                  count = 0
                  if line1[count] in line :
                      count += 1
                      if count == 1 :
                          found = line_no
                      if count == len(line1):
                          not_found = 1
                          print ('String found on line: ' + str(found))
          if not_found == 0 : # for loop ended => line not found
              line_no = -1
              print ('\nString Not found')
      

      【讨论】:

      • 感谢@Bhargav Desai,也尝试过并且有效,但使用了早期版本
      【解决方案3】:

      您需要将整个内容作为字符串 (file.read()) 或尝试:

      found = None
      for idx, line in enumerate(your_file_pointer_here):
          if "second line" in line:
          # or line.endswith()
              found = idx
          elif "This third line" in line:
          # or line.startswith()
              if found and (idx - 1) == found:
                  print("Found the overall needle at {}".format(found))
      

      【讨论】:

      • 感谢@Jan,尝试过也可以,但使用了早期版本
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 2019-10-24
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-03
      相关资源
      最近更新 更多