【问题标题】:Print multiple lines between two specific lines (keywords) from a text file在文本文件的两个特定行(关键字)之间打印多行
【发布时间】:2018-03-11 18:30:52
【问题描述】:

我有一个文本文件,想在 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 错误。 那么有没有办法说:打印“字符:”和“第一场景”之间的所有行?使用索引实际上是不可能的,因为我正在为几部戏剧做这件事,而且它们都有不同数量的角色。

【问题讨论】:

    标签: python python-3.x printing text-files lines


    【解决方案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()
    

    【讨论】:

      【解决方案2】:

      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.
      '''
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-19
        • 2017-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-12
        • 1970-01-01
        相关资源
        最近更新 更多