Python中DFA算法与普通算法在敏感词过滤上的性能对比分析
本文通过Python代码实测对比了DFA(确定有限状态自动机)算法与普通循环查找算法在敏感词过滤场景下的性能差异。实验结果显示,当敏感词数量较少(如100个)时,普通算法效率更高;而当敏感词库扩大至1000个时,DFA算法的优势显现。文章进一步从理论上推导了两种算法的时间复杂度,指出DFA算法的处理时间与敏感词数量基本无关,主要取决于文本长度和词长,从而明确了DFA算法在大规模敏感词库中的适用场景。
具体实现代码如下所示:
#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
import time
class Node(object):
def __init__(self):
self.children = None
# The encode of word is UTF-8
def add_word(root,word):
node = root
for i in range(len(word)):
if node.children == None:
node.children = {}
node.children[word[i]] = Node()
elif word[i] not in node.children:
node.children[word[i]] = Node()
node = node.children[word[i]]
def init(path):
root = Node()
fp = open(path,'r')
for line in fp:
line = line[0:-1]
#print len(line)
#print line
#print type(line)
add_word(root,line)
fp.close()
return root
# The encode of word is UTF-8
# The encode of message is UTF-8
def is_contain(message, root):
for i in range(len(message)):
p = root
j = i
while (j<len(message) and p.children!=None and message[j] in p.children):
p = p.children[message[j]]
j = j + 1
if p.children==None:
#print '---word---',message[i:j]
return True
return False
def dfa():
print '----------------dfa-----------'
root = init('/tmp/word.txt')
#message = '不顾'
print '***message***',len(message)
start_time = time.time()
for i in range(1000):
res = is_contain(message,root)
#print res
end_time = time.time()
print (end_time - start_time)
def is_contain2(message,word_list):
for item in word_list:
if message.find(item)!=-1:
return True
return False
def normal():
print '------------normal--------------'
path = '/tmp/word.txt'
fp = open(path,'r')
word_list = []
print '***message***',len(message)
for line in fp:
line = line[0:-1]
word_list.append(line)
fp.close()
print 'The count of word:',len(word_list)
start_time = time.time()
for i in range(1000):
res = is_contain2(message,word_list)
#print res
end_time = time.time()
print (end_time - start_time)
if __name__ == '__main__':
dfa()
normal()
测试结果如下:
1) 敏感词数量为100个的情况
----------------dfa----------- ***message*** 224 0.325479984283 ------------normal-------------- ***message*** 224 The count of word: 100 0.107350111008
2) 敏感词数量为1000个的情况
----------------dfa----------- ***message*** 224 0.324251890182 ------------normal-------------- ***message*** 224 The count of word: 1000 1.05939006805
通过上述实验数据可以观察到,DFA算法仅在敏感词库规模较大时才体现出显著优势。当敏感词数量仅为百余个时,其执行效率甚至不及普通的字符串查找算法。
接下来从理论层面推导两种算法的时间复杂度。为了便于分析,我们假设消息文本长度均为lenA,且每个敏感词的长度相同,均为lenB,敏感词的总个数为m。
1) DFA算法的核心在于构建一棵多叉树。基于前述假设,敏感词长度一致,因此树的最大深度为lenB。这意味着,从消息文本的任意位置(字节)开始,判断其子串是否匹配敏感词树中的节点,最多只需进行lenB次字符匹配。因此,判断整条消息是否包含敏感词的时间复杂度为lenA * lenB。
2) 再看普通做法,通常采用for循环遍历每个敏感词,并在消息文本中进行查找。假设字符串查找使用KMP算法,其单次查找的时间复杂度为O(lenA + lenB)。
因此,对m个敏感词进行查找的总时间复杂度约为 (lenA + lenB) * m。
综上所述,DFA算法的时间复杂度主要取决于文本长度和词长,基本上与敏感词的个数m无关。
以上关于Python实现敏感词过滤方法的分析即为全部内容,希望能为大家提供有价值的参考。欢迎大家继续支持本站,获取更多技术分享。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













