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

问题描述 投票:-1回答:3

我试图在Python中找到一些函数,该函数可以帮助我找到两个不同字符串的某些单词匹配。例如,我们有2个字符串:

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

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

python string function testing compare
3个回答
1
投票

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

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

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

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


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)

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

© www.soinside.com 2019 - 2024. All rights reserved.