【问题标题】:How to check for keywords in a text file and retrieve multiple segments of text containing the keywords between recurring delimiters如何检查文本文件中的关键字并检索包含重复分隔符之间的关键字的多个文本段
【发布时间】:2017-05-01 17:55:54
【问题描述】:

我有一个包含一些关键字的列表,我正在尝试解析一个文本文件,该文件包含重复分隔符之间的多个文本段。我正在尝试检查每个细分中是否存在关键字。如果存在任何关键字,那么我只想恢复那些包含关键字的段(分隔符之间)。

我的文本文件(ParseInput.txt)如下:

START
cow
sheep
apple
END
//
START
goat
orange
pear
END
//
START
peach
pineapple
watermelon
END
//

我有一个在文本文件中查找关键字的简短 python 脚本:

from sys import argv

script, ParseInput = argv

import re

animal = ['cow', 'sheep', 'python']

inputFile = open(ParseInput)
parseOutput = re.findall('START(.*?)END', inputFile.read(), re.S)

for result in parseOutput:
  for i in animal:
    if i in result:
      print result

运行此脚本会导致以下输出:

cow
sheep
apple

cow
sheep
apple

问题是我只想要一个已恢复段的实例。我认为我的 for/if 循环是问题所在,但我不知道如何解决这个问题,如果有任何建议,我将不胜感激!

【问题讨论】:

    标签: python file parsing text


    【解决方案1】:

    如果存在任何个关键字,那么我只想恢复 包含关键字的那些段(分隔符之间)。

    那就这样做吧!使用any 内置函数:

    for result in parseOutput:
      if any(a in result for a in animal):
          print result
    

    可能值得一试all 内置函数。

    【讨论】:

    • 应该是print(result)
    • @DavidMetcalfe 好吧,我只能推测 OP 正在使用 Python 2,因为他们在自己的代码中将 print 作为语句而不是函数...
    • 我毫不怀疑他们使用的是 Python 2,但 print() 与 v2.6+ 兼容。
    • @DavidMetcalfe 是的,如果你 from __future__ import print_function。它与问题/答案并不真正相关。如果有人想要我的关于此事的建议,人们无论如何都应该使用 Python 3...
    猜你喜欢
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多