如何检查列表中的单词是否包含在另一个列表中的句子中?
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 中的术语 "privacy policy" 更改为 "privac"
junk_terms = ['privac', 'cookie policy', 'copyright']
我希望它不会过滤掉 z 中的任何句子。但是,如果你 运行 它你会看到它仍然过滤掉其中带有 "privacy policy" 的句子,因为它包含字母 "privac"。有没有办法编写这段代码,使其不比较字母而是比较整个单词?
我认为您的代码按预期方式工作。你也可以用列表理解来写它:
print [sentence for sentence in z if not any(term in sentence for term in junk_terms)]
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
表示单词边界和单词之间的匹配,|
表示OR。基本上 \bfoo\b|\bbar\b
将匹配任何包含 foo
作为单词或 bar
作为单词的字符串,并且由于我们 filterfalse()
,它们将被删除。
更新:
对于 python 2,正确的函数是 ifilterfalse()
而不是 filterfalse()
。
我正在网络抓取并试图过滤掉其中包含某些术语的句子。假设我有这个句子列表:
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 中的术语 "privacy policy" 更改为 "privac"
junk_terms = ['privac', 'cookie policy', 'copyright']
我希望它不会过滤掉 z 中的任何句子。但是,如果你 运行 它你会看到它仍然过滤掉其中带有 "privacy policy" 的句子,因为它包含字母 "privac"。有没有办法编写这段代码,使其不比较字母而是比较整个单词?
我认为您的代码按预期方式工作。你也可以用列表理解来写它:
print [sentence for sentence in z if not any(term in sentence for term in junk_terms)]
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
表示单词边界和单词之间的匹配,|
表示OR。基本上 \bfoo\b|\bbar\b
将匹配任何包含 foo
作为单词或 bar
作为单词的字符串,并且由于我们 filterfalse()
,它们将被删除。
更新:
对于 python 2,正确的函数是 ifilterfalse()
而不是 filterfalse()
。