如何从带有字符串的列表中查找不匹配的单词



我有一个类似的字符串

test_string = """
My name is 
My address
My location at 
"""

我有上面字符串中应该出现的单词列表

test_list = ("name","address","city")

我知道我可以使用all函数来确保列表中的所有单词都以字符串形式出现,比如:

if all(x in test_string for x in test_list):
print("All matches")
else:
# Here i want to find the missing items in the list (city)

如何在列表中找到不匹配的单词?

您可以在else块的表达式中对if条件进行否定检查:

test_string = """
My name is 
My address
My location at 
"""
test_list = ("name","address","city")
if all(x in test_string for x in test_list):
print("All matches")
else:
missing = set(x for x in test_list if x not in test_string)
print(missing)
>> {'city'}

第二种方法采用CCD_ 4的CCD_。

测试应用匹配条件后生成的test_list_setmatched集的相等性。如果它们相等,则打印All matches

否则,你会发现这两个集合的差异,这给了你缺失的元素:

test_string = """
My name is 
My address
My location at 
"""
test_list = ("name","address","city")
test_list_set = set(test_list)
matched = set(x for x in test_list if x in test_string )
if matched == test_list_set:
print("All matches")
else:
missing = test_list_set.difference(matched)
print(missing)
>>  {'city'}

您可以从集合中进行检查

test_string = """
My name is 
My address
My location at 
"""
test_list = set(("name","address","city"))
not_included = test_list.difference(set(test_list.split(" "))
if not not_included:
print("All matches")
else:
print("Not included {}".format(not_included))

这将打印所有未包含在testrongtring 中的单词

您可以通过找到不匹配的单词

if len(set(test_string.split()) ^ set(test_list)) > 0:
print("there is unmatched words")
else:
print("All matched")

最新更新