[英]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个字符)。
有专门针对它的任何内置功能:
>>> 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)
我不知道这是否是最快的方式,但对我来说这似乎是最简单的。
我们也可以使用set
intersection
方法
>>> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.