Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在文本文件中搜索多行字符串并在Python中返回行号_Python_Regex_String - Fatal编程技术网

在文本文件中搜索多行字符串并在Python中返回行号

在文本文件中搜索多行字符串并在Python中返回行号,python,regex,string,Python,Regex,String,我试图在文本文件中搜索并匹配两行中的部分或全部文本。 我需要返回第一行匹配字符串的文本文件中的行号 示例文本文件可以是: 这是第一行的一些文字 这是更多或第二行 第三行有更多的文本 如果我试图在第二行和第三行中找到以下字符串,它将返回行号2,如果0是第一行,则返回行号1 我看过许多类似的例子,似乎我应该使用重新包装,但我也无法确定如何返回行号 此代码跨多行查找字符串 import re a = open('example.txt','r').read() if re.findall('seco

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

示例文本文件可以是:

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

如果我试图在第二行和第三行中找到以下字符串,它将返回行号2,如果0是第一行,则返回行号1

我看过许多类似的例子,似乎我应该使用重新包装,但我也无法确定如何返回行号

此代码跨多行查找字符串

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

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

您可能需要将整个内容作为字符串文件。请阅读或尝试:

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

您可能需要将整个内容作为string 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))
使用.count和match对象计算匹配前的换行数:

进口稀土 将“example.txt”、“r”作为文件打开: content=file.read 匹配=重新搜索“第二行\n第三行”,内容 如果匹配: 打印“在第行找到匹配项”,内容。计数“\n”,0,匹配。开始 match.start是内容中匹配开始的位置

content.count'\n',0,match.start统计内容中字符位置0和匹配开始之间的换行数

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

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

进口稀土 将“example.txt”、“r”作为文件打开: content=file.read 匹配=重新搜索“第二行\n第三行”,内容 如果匹配: 打印“在第行找到匹配项”,内容。计数“\n”,0,匹配。开始 match.start是内容中匹配开始的位置

content.count'\n',0,match.start统计内容中字符位置0和匹配开始之间的换行数


如果您希望行号从1开始而不是从0开始,请使用1+内容。计数'\n',0,match.start。

这可能适用于您:

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

这可能对你有用:

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,也尝试过并且有效,但是使用了早期版本的anks@Bhargav Desai,也尝试过并且有效,但是使用了早期版本的anks@Jan,尝试过并且有效,但是使用了早期版本的anks@Jan,尝试过并且有效,但是使用了早期版本