【问题标题】:If I have a list of words, how can I check if string does not contain any of the words in the list, and efficiently?如果我有一个单词列表,如何有效地检查字符串是否不包含列表中的任何单词?
【发布时间】:2012-06-17 01:15:23
【问题描述】:

正如标题所说,我有一个单词列表,例如stopWords = ["the", "and", "with", etc...],我收到了诸如“杀死狐狸和狗”之类的文字。我想要像“杀死狐狸狗”这样的输出非常有效和快速。我该怎么做(我知道我可以使用 for 循环进行迭代,但这不是很有效)

【问题讨论】:

    标签: python search loops filter stop-words


    【解决方案1】:

    使用list comprehension

    stopWords = ["the", "and", "with"]
    msg = "kill the fox and the dog"
    
    ' '.join([w for w in msg.split() if w not in stopWords])
    

    给予:

    'kill fox dog'
    

    【讨论】:

    • w not in stopWords 会随着 stopWords 变长而变慢,因为它必须遍历列表来检查每一个。这就是为什么将 stopWords 设为一个集合很重要的原因
    • @gnibbler 好的,请注意,谢谢。总是乐于学习新东西(我几乎不经常使用集合)
    【解决方案2】:

    最重要的改进是将 stopWords 设为set。这意味着查找将非常快

    stopWords = set(["the", "and", "with", etc...])
    " ".join(word for word in msg.split() if word not in stopWords)
    

    如果您只想知道文本中是否有任何停用词

    if any(word in stopWords for word in msg.split()):
        ...
    

    【讨论】:

    • 比制作正则表达式更高效吗?
    • @mlt,可能不是。这项工作与此如此不同,以至于很难猜测。您应该使用正则表达式编写答案
    【解决方案3】:
    1. 将原始单词列表放入字典中。
    2. 遍历给定字符串中的字符,使用空格作为单词的分隔符。在字典中查找每个单词。

    【讨论】:

      【解决方案4】:

      使用 Python,最快的操作是将“停用词”设置为集合而不是列表,并使用“停用词中的 x”直接检查成员资格。这种结构旨在为此类操作提供快速的操作。

      See the set documentation

      【讨论】:

        【解决方案5】:

        将您的停用词放在set() 中(正如其他人所建议的那样),将您的其他单词累积到一个工作集中,然后简单地使用working = working - stopWords 获取集合差异......以过滤所有停用词的工作集出它。或者只是为了检查这些词的存在使用条件。例如:

        #!python
        stopWords = set('the a an and'.split())
        working   = set('this is a test of the one working set dude'.split())
        if working == working - stopWords:
            print "The working set contains no stop words"
        else:
            print "Actually, it does"
        

        实际上有更高效的数据结构,例如trie,它可以用于大的、相对密集的停用词集。你可以找到 Python 的 trie 模块,尽管我没有看到任何写成二进制 (C) 扩展的模块,我想知道在纯 Python 中实现的 trie 与使用 Python 的 set() 支持之间的交叉点在哪里。 (不过,Cython 也可能是一个很好的例子)。

        事实上,我看到有人在这里单独解决了这个问题SO: How do I create a fixed length mutable array of python objects in cython

        当然,最终,您应该创建简单的基于集合的版本,对其进行测试和分析,然后,如有必要,尝试尝试 trie 和 Cython-trie 变体作为可能的改进。

        【讨论】:

          【解决方案6】:

          作为替代方案,您可以将列表组合在一个正则表达式中,并将停用词和周围的空格替换为一个空格。

          import re
          stopWords = ["the", "and", "with"]
          input = "Kill the fox and dog"
          pattern = "\\s{:s}\\s".format("\\s|\\s".join(stopWords))
          print(pattern)
          print(re.sub(pattern, " ", input))
          

          会输出

          \sthe\s|\sand\s|\swith\s
          Kill fox dog
          

          【讨论】:

            猜你喜欢
            • 2018-07-29
            • 2017-10-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-10-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多