简体   繁体   中英

How to check if whole words from string are contained in other string?

I want my program to return True if one word from a string is the same as a word in another string, but only when the whole word is matching and not single letters or parts. Here's an illustration on what I mean...

a = "hi please help"
b = "help anyone"

if any(a.split()) == any(b.split()):
    print("True")

this works for the time being, but if I swap a for something else...

a = "h"
b = "help"

if any(a.split()) == any(b.split()):
    print("True")

it still prints "True", which is not my intention. I did look at other similar threads to this, but I couldn't find any that solved the problem where parts are not accepted, but the whole string doesn't have to be a substring.

Try this:

set_a = set(a.split())
any(w in set_a for w in b.split())

This will evaluate to True if any word w from b.split() is in set_a , where set_a is a set of words formed from a.split() .

This should be faster than doing set intersection, since (1) it only creates a set for one of the split strings, (2) it stops searching as soon as a match is found, and (3) it doesn't create a set for the intersection result.

Convert both strings to sets and create an intersection:

if set(a.split()) & set(b.split()):
    print("True")

Try this :

for i in b.split():
  if a.split().count(i):
    print("True")

这应该有效: any([e in a.split() for e in b.split()])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM