如何检查文本文件中的关键字并检索包含重复分隔符之间关键字的多段文本

2024-04-18 23:47:36 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的文本文件(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循环是问题所在,但我不知道如何解决这个问题,如果您有任何建议,我将不胜感激!你知道吗


Tags: inimportre脚本applefor关键字result
1条回答
网友
1楼 · 发布于 2024-04-18 23:47:36

If any of keywords are present, then I would only like to recover those segments (between delimiters) that contain the keywords.

那就这么做吧!使用^{}内置函数:

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

可能值得在使用时检查一下^{}内置。你知道吗

相关问题 更多 >