Python3.4:对于文本中的每一行

时间:2016-01-17 22:56:22

标签: python for-loop python-3.4

我有这段代码:

for x in adele_text:
    if "Hello, its me" in x:
        print (x)

打印“Hello,it me”的行。我希望能够打印下一行,以及此行之后的行。如何在此之前打印下一行x和x行呢?

有没有办法打印最后2个句子?句子用“。”分隔。

1 个答案:

答案 0 :(得分:2)

您可以使用内置的next()

number_of_lines_to_print = 2

with open(filename) as adele_text:
    for line in adele_text:
        if "Hello, its me" in line:
            # printing next "number_of_lines_to_print" lines
            for _ in range(number_of_lines_to_print):
                print(next(adele_text, ''))
            break  # remove if you want to continue searching the file

请注意next(adele_text, '')中的空字符串非常重要 - 如果我们位于文件的末尾,则有助于避免引发StopIteration exception