![](/img/trans.png)
[英]How to check if a list of words is contained in another list in a pandas dataframe?
[英]How do I check if words in a list are contained in sentences in another list?
我正在抓取网页,并尝试过滤掉其中带有某些术语的句子。 假设我有以下句子列表:
z = ['a privacy policy', 'there are many standard challenges that face every business']
我想过滤掉其中包含此列表中所有单词的句子:
junk_terms = ['privacy policy', 'cookie policy', 'copyright']
所以我做:
for sentence in z:
if all(term not in sentence for term in junk_terms):
print sentence
它印出了there are many standard challenges that face every business
到现在为止还挺好。 但是,我注意到它与junk_terms中的术语与z中的整个术语不匹配。 它正在查看junk_terms中是否有字母出现在z中。 例如,让我们将junk_terms中的术语“隐私策略”更改为“ privac”
junk_terms = ['privac', 'cookie policy', 'copyright']
我希望它不会过滤出z中的任何句子。 但是,如果运行它,则会看到它仍然过滤掉其中带有“隐私策略”的句子,因为它包含字母“ privac”。 有没有一种方法可以编写此代码,使它不比较字母而是比较整个单词?
re可能正是您想要的。 结果是所有未过滤的字符串。 这样,您还可以捕获包含以点或逗号结尾的垃圾表达式的字符串。
import re
import itertools
# All of the strings
z = ['a privacy policy', 'there are many standard challenges that face every business']
junk_terms = ['privacy policy', 'cookie policy', 'copyright']
# Build the regex, making sure we don't capture parts.
regex = re.compile("|".join(r"\b{}\b".format(term) for term in junk_terms))
# Filter out anything that we found junk in.
result = list(itertools.filterfalse(regex.search, z))
关于re的说明: \\b
表示单词边界,单词之间匹配,而|
表示“或”。 基本上\\bfoo\\b|\\bbar\\b
会匹配任何字符串foo
作为一个字或bar
作为一个词,因为我们filterfalse()
它们将被退学了。
更新:
对于python 2,正确的函数是ifilterfalse()
而不是filterfalse()
。
我认为您的代码按预期方式工作。 您还可以使用列表理解来编写它:
print [sentence for sentence in z if not any(term in sentence for term in junk_terms)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.