[英]Search Python for a keyword then return the keyword
如何在 python 中的句子中搜索關鍵字,然后返回該關鍵字。 該句子將是動態的,它們的關鍵字列表將是 static。
sentences = "My name is sing song. I am a mother. I am happy. You sing like my mother".split(".")
search_keywords=['mother','father','son']
我要回媽媽這個詞? 我想不通。
我認為你不需要在.
除非您想分別評估每個句子
這將評估整個句子並返回列表中匹配的每個單詞:
編輯:添加正則表達式以僅查找整個單詞
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)
Output:
['mother']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.