[英]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.