Python 打印文本文件中两个特定行(关键字)之间的多行
我有一个文本文件,希望在Windows上使用Python 3.5打印另外两行之间的行。我想将一部戏剧的角色打印到另一个文件中。文本文件如下所示:Python 打印文本文件中两个特定行(关键字)之间的多行,python,python-3.x,printing,text-files,lines,Python,Python 3.x,Printing,Text Files,Lines,我有一个文本文件,希望在Windows上使用Python 3.5打印另外两行之间的行。我想将一部戏剧的角色打印到另一个文件中。文本文件如下所示: ... Characters: Peter, the king. Anna, court lady. Michael, caretaker. Andre, soldier. Tina, baker. First scene. ... 我想打印“Characters:”和“First scene”两行之间的所有角色名称。我的第一次尝试是: newfil
...
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错误。
那么,有没有一种方法可以说:打印“角色:”和“第一场景”之间的所有行?使用索引实际上是不可能的,因为我正在为几部戏剧制作索引,它们都有不同数量的角色。a
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()