我有 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'])
关于python - 检查字符串是否包含列表中的任何单词的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27781506/