【问题标题】:How do I check if words in a list are contained in sentences in another list?如何检查列表中的单词是否包含在另一个列表中的句子中?
【发布时间】:2016-03-13 21:50:09
【问题描述】:

我正在网页抓取并试图过滤掉其中包含某些术语的句子。假设我有这个句子列表:

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”。有没有办法编写此代码,以便它不比较字母而是比较整个单词?

【问题讨论】:

  • 如果你想让它与垃圾词中的任何单词匹配,你应该选择any而不是all
  • 为什么您认为在更改您的 junk_terms 后它不应该打印任何内容?

标签: python string list set


【解决方案1】:

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()

【讨论】:

  • 当我尝试运行它时,我收到一条错误消息,上面写着“AttributeError: 'module' object has no attribute 'filterfalse'”也许它已被弃用。我正在使用 python 2.7。
  • @Mika Schiller 我已经相应地更新了我的答案。
【解决方案2】:

我认为您的代码按预期方式工作。你也可以用列表推导式来写:

print [sentence for sentence in z if not any(term in sentence for term in junk_terms)]

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 2021-07-16
    • 2018-04-03
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 1970-01-01
    相关资源
    最近更新 更多