我如何在python中搜索一个句子的关键词,然后返回这个关键词。句子将是动态的,他们的关键字列表将是静态的。
sentences = "My name is sing song. I am a mother. I am happy. You sing like my mother".split(".")
search_keywords=['mother','father','son']
我想返回母亲这个词?我想不明白这个问题。
我不认为你需要在句子中拆分出 .
除非你想分别评价每个句子
这将评估整个句子,并从列表中返回每个匹配的单词。
EDIT: 添加了regex,只查找完整的单词。
import re
def string_found(string1, string2):
return re.search(r"\b" + re.escape(string1) + r"\b", string2)
def find_words(text, words):
return [word for word in words if string_found(word, text)]
sentences = "My name is sing song. I am a mother. I am happy. You sing like my mother"
search_keywords=['mother', 'father', 'son']
found = find_words(sentences, search_keywords)
print(found)
产出:
['mother']