检查字符串是否包含列表中的任何单词的最快方法

Fastest way to check does string contain any word from list

我有 Python 个申请。

有 450 个禁止短语的列表。有来自用户的消息。我想检查一下,此消息是否包含任何此类禁止的短语。最快的方法是什么?

目前我有这个代码:

message = "sometext"
lista = ["a","b","c"]

isContaining = false

for a, member in enumerate(lista):
 if message.contains(lista[a]):
  isContaining = true
  break

有没有更快的方法?我需要在不到 1 秒的时间内处理消息(最多 500 个字符)。

any内置函数专门用于:

>>> message = "sometext"
>>> lista = ["a","b","c"]
>>> any(a in message for a in lista)
False
>>> lista = ["a","b","e"]
>>> any(a in message for a in lista)
True

或者您可以检查集合的交集:

>>> lista = ["a","b","c"]
>>> set(message) & set(lista)
set([])
>>> lista = ["a","b","e"]
>>> set(message) & set(lista)
set(['e'])
>>> set(['test','sentence'])&set(['this','is','my','sentence'])
set(['sentence'])

但是您将无法检查子词:

>>> set(['test','sentence'])&set(['this is my sentence'])

我会将 any 内置函数与 in 运算符结合使用:

isContaining = any(a in message for a in lista)

我不知道这是否是最快的方法,但对我来说它似乎是最简单的。

使用regex compile from list

考虑内存和构建时间或表达式,提前编译。

lista = [...]
lista_escaped = [re.escape(item) for item in lista]
bad_match = re.compile('|'.join(lista_escaped))
is_bad = bad_match.search(message, re.IGNORECASE)

我们也可以用setintersection的方法

>>> message = "sometext"
>>> lista = ["a","b","c"]
>>> isContaining = False
>>> if set(list(message)).intersection(set(lista)):
...    isContaining = True
... 
>>> isContaining
False
>>> message = "sometext a"
>>> list(message)
['s', 'o', 'm', 'e', 't', 'e', 'x', 't', ' ', 'a']
>>> if set(list(message)).intersection(set(lista)):
...    isContaining = True
... 
>>> isContaining
True