DFA 算法实现关键词匹配

起因: 从网页中爬去的页面。须要推断是否跟预设的关键词匹配(是否包括预设的关键词),并返回全部匹配到的关键词 。


眼下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()

请再阅读我的这篇文章
http://blog.csdn.net/woshiaotian/article/details/10047675

转载于:https://www.cnblogs.com/mfmdaoyou/p/7352391.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值