[英]List Comprehension for items in list
list comprehension to check for presence of any of the items. 列出理解以检查是否存在任何项目。
I have some text and would like to check on some keywords. 我有一些文字,想检查一些关键词。 It should return me the sentence if it contains any of the keywords.
如果它包含任何关键字,它应该返回我的句子。
An example: 一个例子:
text = [t for t in string.split('. ')
if 'drink' in t or 'eat' in t
or 'sleep' in t]
This works. 这可行。 However, I am thinking if there is a better way, as the list of keywords may grow.
但是,我正在考虑是否有更好的方法,因为关键字列表可能会增加。
I tried putting the keywords in a list but it would not work in this list comprehension. 我尝试将关键字放在列表中,但在此列表理解中不起作用。 OR using if any
或使用(如果有)
pattern = ['drink', 'eat', 'sleep']
[t for t in string.split('. ') if any (l in pattern for l in t)]
You were almost there: 您几乎在那里:
pattern = ['drink', 'eat', 'sleep']
[t for t in string.split('. ') if any(word in t for word in pattern)]
The key is to check for each word in pattern if that work is inside the sentence: 关键是检查模式中的每个单词是否在句子中:
any(word in t for word in pattern)
Your use of any
is backwards. 您对
any
使用都是向后的。 This is what you want: 这就是你想要的:
[t for t in string.split('. ') if any(l in t for l in pattern)]
An alternative approach is using a regex: 另一种方法是使用正则表达式:
import re
regex = '|'.join(pattern)
[t for t in string.split('. ') if regex.search(t)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.