检查字符串是否包含列表中任何单词的最快方法 [英] Fastest way to check does string contain any word from list
本文介绍了检查字符串是否包含列表中任何单词的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有Python应用程序.
I have Python application.
有450个禁止的短语列表.有来自用户的消息.我想检查一下,此消息是否包含任何这种禁止的言词.最快的方法是什么?
There is list of 450 prohibited phrases. There is message got from user. I want to check, does this message contain any of this prohibited pharases. What is the fastest way to do that?
当前我有以下代码:
message = "sometext"
lista = ["a","b","c"]
isContaining = false
for a, member in enumerate(lista):
if message.contains(lista[a]):
isContaining = true
break
有没有更快的方法呢?我需要在不到1秒的时间内处理消息(最多500个字符).
Is there any faster way to do that? I need to handle message (max 500 chars) in less than 1 second.
推荐答案
有 any 专用于此的内置函数:
There is the any built-in function specially for that:
>>> 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
或者,您可以检查集合的交集:
Alternatively you could check the intersection of the sets:
>>> 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'])
但是您将无法检查子词:
But you won't be able to check for subwords:
>>> set(['test','sentence'])&set(['this is my sentence'])
这篇关于检查字符串是否包含列表中任何单词的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文