gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:01:56 24 4
gpt4 key购买 nike

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

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

最佳答案

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

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

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

可能值得查看 all当您使用时内置。

关于python - 如何检查文本文件中的关键字并检索包含重复分隔符之间的关键字的多个文本段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43723883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com