注意,这不是这个问题的重复:
How to check if a string contains an element from a list in Python
但是,这是基于它的逻辑。
我有以下字符串:
my_string = 'this is my complex description'
我有一个关键字列表:
keywords = ['my', 'desc', 'complex']
我知道我可以使用以下方法检查关键字是否存在:
if any(ext in my_string for ext in keywords):
print(my_string)
但我想显示哪些关键字与描述实际匹配。我知道我可以对关键字进行循环,然后分别检查每个关键字,但是否可以在一条语句中进行?
哪个版本的 python 是解决方案并不重要。
请您参考如下方法:
如果你想匹配完整的单词,你可以使用set intersection:
>>> my_string = 'this is my complex description'
>>> keywords = ['my', 'desc', 'complex']
>>> set(my_string.split()) & set(keywords)
{'complex', 'my'}
