Fork me on GitHub

版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | https://vearne.cc

起因: 从网页中爬去的页面,需要判断是否跟预设的关键词匹配(是否包含预设的关键词),并返回所有匹配到的关键词 。

目前pypi 上两个实现

ahocorasick
https://pypi.python.org/pypi/ahocorasick/0.9
esmre
https://pypi.python.org/pypi/esmre/0.3.1

但是其实包都是基于DFA 实现的
这里提供源码如下:

#!/usr/bin/python2.6  
# -*- coding: utf-8 -*-
import time
class Node(object):
    def __init__(self):
        self.children = None
        # 标记匹配到了关键词
        self.flag = False


# The encode of word is UTF-8
def add_word(root,word):
    if len(word) <= 0:
        return    
    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]]
    node.flag = True


def init(word_list):
    root = Node()
    for line in word_list:
        add_word(root,line)
    return root

# The encode of word is UTF-8
# The encode of message is UTF-8
def key_contain(message, root):
    res = set() 
    for i in range(len(message)):
        p = root
        j = i
        while (j<len(message) and p.children!=None and message[j] in p.children):
            if p.flag == True:
                res.add(message[i:j])
            p = p.children[message[j]]
            j = j + 1

        if p.children==None:
            res.add(message[i:j])
            #print '---word---',message[i:j]
    return res 



def dfa():
    print '----------------dfa-----------'
    word_list = ['hello', '民警', '朋友','女儿','派出所', '派出所民警']
    root = init(word_list)

    message = '四处乱咬乱吠,吓得家中11岁的女儿躲在屋里不敢出来,直到辖区派出所民警赶到后,才将孩子从屋中救出。最后在征得主人同意后,民警和村民合力将这只发疯的狗打死'
    x = key_contain(message, root)    
    for item in x:
        print item



if __name__ == '__main__':
    dfa()

测试结果:
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算法,KMP算法的时间复杂度是O(lenA + lenB)

那么对m个敏感词查找的时间复杂度是 (lenA + lenB ) * m

综上所述,DFA 算法的时间复杂度基本上是与敏感词的个数无关的。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据