Python查找含任一关键词的文本片段
如果我要在文本片段中查找是否含有多个关键词中的至少一个,代码如下:
keywords = ['美女','大长腿','翘臀']
string = '我:"前面那个美女,等一下,你有东西落在我这了",美女:"什么东西?",我:"你"'
string2 = '一键三连支持一下,拜托啦!'
print([i in string for i in keywords])
if any([i in string for i in keywords]):
print(string)
print([i in string2 for i in keywords])
#不加方括号也行
if any(i in string2 for i in keywords):
print(string2)
[True, False, False]
我:"前面那个美女,等一下,你有东西落在我这了",美女:"什么东西?",我:"你"
[False, False, False]
参考链接:https://www.runoob.com/python/python-func-any.html
Python any() 函数
描述
any() 函数用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。
元素除了是 0、空、FALSE 外都算 TRUE。
函数等价于:
def any(iterable):
for element in iterable:
if element:
return True
return False
Python 2.5 以上版本可用。
语法
以下是 any() 方法的语法:
any(iterable)
参数
- iterable – 元组或列表。
返回值
如果都为空、0、false,则返回false,如果不都为空、0、false,则返回true。
实例
以下展示了使用 any() 方法的实例:
>>>any(['a', 'b', 'c', 'd']) # 列表list,元素都不为空或0
True
>>> any(['a', 'b', '', 'd']) # 列表list,存在一个为空的元素
True
>>> any([0, '', False]) # 列表list,元素全为0,'',false
False
>>> any(('a', 'b', 'c', 'd')) # 元组tuple,元素都不为空或0
True
>>> any(('a', 'b', '', 'd')) # 元组tuple,存在一个为空的元素
True
>>> any((0, '', False)) # 元组tuple,元素全为0,'',false
False
>>> any([]) # 空列表
False
>>> any(()) # 空元组
False