簡體   English   中英

在文本文件的兩個特定行(關鍵字)之間打印多行

[英]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.
...

我想在“字符:”和“第一個場景”之間打印所有字符名稱。 我的第一次嘗試是:

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。 因此,有一種說法:打印“字符:”和“第一場景”之間的所有行嗎? 索引實際上是不可能的,因為我正在為幾部戲做這件事,而且它們都有不同數量的角色。

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM