在 python 中的特定行之后提取一行

Extracting a line after a specific line in python

我有这个问题,我正在尝试提取 A 和 B 两行。但是如果 B 在 A 之后出现,我将提取这些行,否则,我想通过。最初,我认为它们与我使用下面的代码的数量相等。它实际上是更大代码的一部分,但这是主要问题所在。

def get_line(file_name, find_word1, find_word2):

    lines = []
    for line in file_name.strip().split('\n'):
        if find_word1 in line:
            lines.append(line)
        elif find_word2 in line:
            lines.append(line)
        else:
            pass
    return lines

就像 find_word1Afind_word2B。 从我的代码中,我知道我只能得到两行而不是条件。我不知道该怎么做。如果你能帮忙,请帮忙 谢谢

def get_line(file_name, find_word1, find_word2):
    lines = []
    temp = ""

    for line in file_name.strip().split('\n'):
        if find_word1 in line and not temp:
            temp = line
        elif find_word2 in line and temp:
                lines.append(temp)
                lines.append(line)
                temp = ""
        else:
            pass

    return lines
def get_line(file_name, find_word1, find_word2):
    lines = []
    firstWord = False
    for line in file_name.strip().split('\n'):
        if find_word1 in line and not firstWord:
            firstWord = True
            temp = line
        elif find_word2 in line and firstWord:
            lines.append(temp)
            lines.append(line)
            firstWord = False
            temp = ""
    return lines

您需要对A进行初步检查,只有找到A您才关心B。否则B无关紧要。这是通过检查 A 是否在该行中并且尚未找到来实现的。找到 A 后,可以使用布尔值来标记它已找到,并且从那时起只查找 B。