[英]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.如果字符串中的一个单词与另一个字符串中的单词相同,我希望我的程序返回 True,但仅当整个单词匹配而不是单个字母或部分匹配时。 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.它仍然打印“True”,这不是我的意图。 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()
.如果来自b.split()
任何单词w
在set_a
,这将评估为True
,其中set_a
是由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.这应该比设置交集更快,因为(1)它只为一个拆分字符串创建一个集合,(2)它一旦找到匹配就停止搜索,以及(3)它不创建一个集合为交集结果。
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()])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.