gpt4 book ai didi

python - 使用 python 提取包含关键字或短语列表的句子

转载 作者:行者123 更新时间:2023-12-02 20:58:29 25 4
gpt4 key购买 nike

我使用以下代码从文件中提取一个句子(该句子应包含部分或全部搜索关键字)

search_keywords=['mother','sing','song']
with open('text.txt', 'r') as in_file:
text = in_file.read()
sentences = text.split(".")

for sentence in sentences:
if (all(map(lambda word: word in sentence, search_keywords))):
print sentence

上述代码的问题是,如果其中一个搜索关键字与句子单词不匹配,它不会打印所需的句子。我想要一个代码来打印包含部分或全部搜索关键字的句子。如果代码还可以搜索短语并提取相应的句子,那就太好了。

最佳答案

您似乎想计算每个句子中 search_keyboards 的数量。您可以按如下方式执行此操作:

sentences = "My name is sing song. I am a mother. I am happy. You sing like my mother".split(".")
search_keywords=['mother','sing','song']

for sentence in sentences:
print("{} key words in sentence:".format(sum(1 for word in search_keywords if word in sentence)))
print(sentence + "\n")

# Outputs:
#2 key words in sentence:
#My name is sing song
#
#1 key words in sentence:
# I am a mother
#
#0 key words in sentence:
# I am happy
#
#2 key words in sentence:
# You sing like my mother

或者,如果您只想要具有最匹配 search_keywords 的句子,您可以创建一个字典并查找最大值:

dct = {}
for sentence in sentences:
dct[sentence] = sum(1 for word in search_keywords if word in sentence)

best_sentences = [key for key,value in dct.items() if value == max(dct.values())]


print("\n".join(best_sentences))

# Outputs:
#My name is sing song
# You sing like my mother

关于python - 使用 python 提取包含关键字或短语列表的句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39455363/

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