如何检查字符串中的任何单词是否与另一个字符串匹配

时间:2019-12-19 15:29:35

标签: python string

我正在尝试在Python中找到一些函数,该函数可以帮助我找到两个不同字符串的某些单词匹配项。

例如,我们有2个字符串:

  1. “我每天都在打篮球”
  2. “篮球是有史以来最糟糕的比赛”

如果在两个字符串中都找到“篮球”,我希望此函数返回true。

3 个答案:

答案 0 :(得分:2)

您可以找到两个短语中的常用词:

common_words = set(phrase1.split()).intersection(phrase2.split())

您可以通过简单地检查单词是否在common_words集中(例如:if word in common_words: ...)来检查两个短语中是否都包含单词。

您还可以检查此集合有多少个元素。如果len(common_words) == 0phrase1phrase2不包含常用词。

答案 1 :(得分:0)

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)

答案 2 :(得分:0)

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!"

请参阅:Python - Check If Word Is In A String