在列表和字符串中查找匹配的单词

cli*_*ray 5 python string comparison performance list

我正在用Python编写一些代码,我想检查一个单词列表是否在长字符串中.我知道我可以多次迭代它,这可能是同样的事情,但我想看看是否有更快的方法来做到这一点.我目前正在做的是:

    all_text = 'some rather long string'
    if "motorcycle" in all_text or 'bike' in all_text or 'cycle' in all_text or 'dirtbike' in all_text:
        print 'found one of em'
Run Code Online (Sandbox Code Playgroud)

但我想要做的是:

keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
if item in keyword_list in all_text:
            print 'found one of em'
Run Code Online (Sandbox Code Playgroud)

无论如何有效地做到这一点?我意识到我能做到:

keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']
for item in keyword_list:
      if item in all_text:
            print 'found one of em'
Run Code Online (Sandbox Code Playgroud)

但是一旦关键字列表变长,似乎会有更好的方法.

Pav*_*sov 15

你仍然必须至少检查它们,直到找到一个在文本中,但它可以更简洁:

keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']

if any(word in all_text for word in keyword_list):
    print 'found one of em'
Run Code Online (Sandbox Code Playgroud)

  • 您可以将“keyword_list”放入“set”中 (2认同)

Rak*_*esh 6

这个怎么样。

>>> keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike', "long"]
>>> all_text = 'some rather long string'
>>> if set(keyword_list).intersection(all_text.split()):
...     print "Found One"
Found One
Run Code Online (Sandbox Code Playgroud)


Pet*_*nov 5

一种方法是从关键字列表中构建前缀树。然后,您可以遍历每个字符的长字符串字符。在每次迭代中,您尝试在前缀树中找到从当前位置开始的大字符串中的前缀。此操作需要O(log k)时间,其中关键字列表的大小为k(假设前缀树是平衡的)。如果长字符串的长度为n,则总复杂度为just O(n log k)O(n k)如果k大则幼稚。


Sha*_*awn 5

使用正则表达式可能是最快的方法。

re.findall(r'motorcycle|bike|cycle|dirtbike', text)
Run Code Online (Sandbox Code Playgroud)

将返回所选单词的所有匹配项。