从文本文件中打印两个特定行(关键字)之间的多行

Print multiple lines between two specific lines (keywords) from a text file

我有一个文本文件,想打印其他两行之间的行,在 Windows 上使用 Python 3.5。我想将戏剧中的角色打印到另一个文件中。文本文件如下所示:

...
Characters:
Peter, the king.
Anna, court lady.
Michael, caretaker.
Andre, soldier.
Tina, baker.
First scene.
...

我想打印 "Characters:" 和 "First scene." 行之间的所有字符名称我的第一次尝试是:

newfile = open('newfile.txt', 'w')
with open('drama.txt', 'r') as f:
for line in f:
    if line.startswith('Characters:'):
        print(next(f), file = newfile)

但这只打印一行,我需要几行,并且使用 next() 函数的迭代总是在打印一行后导致 StopIteration 错误。 那么有没有办法说:打印行 "Characters:" 和 "First Scene." 之间的所有行?使用索引实际上是不可能的,因为我正在为几部戏剧做这件事,而且它们都有不同数量的角色。

一个regex解决方案:

import re
f = open('drama.txt', 'r')
content = f.read()
x = re.findall(r'Characters:(.*?)First scene\.', content, re.DOTALL)
print("".join(x))

'''
Peter, the king. 
Anna, court lady. 
Michael, caretaker. 
Andre, soldier. 
Tina, baker.
'''

您可以设置一个布尔值来知道是否打印一行:

newfile = open('newfile.txt', 'w')

printing = False

with open('drama.txt', 'r') as f:
    for line in f:
        if line.startswith('Characters:'):
            printing = True
            continue # go to next line
        elif line.startswith('First scene'):
            printing = False
            break # quit file reading

        if printing:
            print(line, file=newfile)
newfile.close()