如何在文本文件中找到一个词并打印下一行 Python 中的另一个词

How to find a word in a text file and print another that is in the next line in Python

我有一个充满文本的文本文件,每次某个单词出现在一行中时,下一行是我想在另一个文本文件中打印的数字。我一直在使用枚举来查找单词旁边的数字,但我想要下一行中的数字。例如,这是文本文件:

Line 1: Hello bye
Line 2: 23
Line 3: Adios bye
Line 4: 45

我想让程序找到单词 bye 并打印 23 和 45。现在我只能找到 Hello 并打印 bye。如何让它打印以下行?谢谢。

您可以搜索每一行,然后移动到下一行,如下所示:

with open('text.txt','r') as f:
    for line in f:
        phrase = 'bye'
        if phrase in line: #if the phrase is present
            next(f) #move to next line

你可以用下面的几行做任何你想做的事;如果您要查找数字,则可以使用 .isdigit() 假设该行仅包含数字。

一个可能的替代解决方案是使用正则表达式:

import re

def hasNumber(string):
    return bool(re.search(r'\d', string)) #returns true/false

with open('text.txt','r') as f:
    for line in f:
        if re.match('bye',line): #if it contains the word "bye"
            newline = next(f) #declare the next line
            if hasNumber(newline): #if that line contains any numbers
                number = re.compile(r'\d') #find those numbers
                print(''.join(number.findall(newline)[:])) #print those numbers

如果第二个变量匹配第一个变量,re.match 函数 returns 为真(虽然这不是严格意义上的,因为它只对条件起作用)。