[英]Python match at least 3 words in a set
我有一個短語 str,例如:
phrase = "My cat has two eyes and like to catch rats"
我有一組words
,我想匹配短語中至少 3 個這些單詞。
words = set(["eyes", "like", "cat"])
目前我有以下代碼
found = bool(set(phrase.lower().split()) & words)
但如果短語中有任何單詞,它就會匹配,並且我想要至少 3 個單詞匹配。
我能做些什么來實現這一目標? 我不想使用regex
。
您可以檢查交叉點的長度是否至少為 3。
found = len(set(phrase.lower().split()).intersection(words)) >= 3
您可以執行以下操作:
from typing import Set
def words_matcher(phrase: str, words: Set[str], threshold: int = 3) -> bool:
phrase_as_set = set(phrase.lower().split())
common_words = phrase_as_set.intersection(words)
return len(common_words) >= threshold
你快到了。 &
對set
對象進行交集。 但不是做bool
,您需要獲取length
並檢查它是否 >=3。 因此使用這個:
>>> phrase = "My cat has two eyes and like to catch rats"
>>> words = set(["eyes", "like", "cat"])
>>> len(set(phrase.lower().split()) & words) >= 3
True
如果你想檢查你的集合中的所有單詞是否都出現在短語中,你可以檢查它是否是子集,即
phrase = "My cat has two eyes and like to catch rats"
words = set(["eyes", "like", "cat"])
print(words.issubset(phrase.lower().split())) # True
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.