我试图在Python中找到一些函数,该函数可以帮助我找到两个不同字符串的某些单词匹配。例如,我们有2个字符串:
并且我希望如果在两个字符串中都找到“篮球”,此函数将返回true。
您可以找到两个短语中的常用词:
common_words = set(phrase1.split()).intersection(phrase2.split())
您可以通过简单地检查单词是否在common_words
集中(例如:if word in common_words: ...
)来检查两个短语中是否都包含单词。
您还可以检查此集合中有多少个元素。如果len(common_words) == 0
,则phrase1
和phrase2
不包含常用词。
l = ["I am playing basketball everyday", "basketball is the worst game ever"]
for x in l:
print (x)
if "basketball" in x.lower():
print (True)
str1 = "I am playing basketball everyday"
str2 = "basketball is the worst game ever"
if "basketball" in str1 and "basketball" in str2:
print "basketball is in both strings!"