我有一个文本文件,想要在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 Error。 那么有没有办法说:打印“Characters:”和“First Scene”这两行之间的所有行?使用索引并不是真的可行,因为我正在为几部戏剧做这件事并且他们拥有不同数量的角色。
答案 0 :(得分:1)
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.
'''
答案 1 :(得分:1)
您可以设置布尔值以了解是否要打印一行:
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()