Cause: A page crawled from a Web page. It is necessary to infer whether to match the predefined keywords (including the preset keywords) and return all the matching keywords.
Two implementations of the PyPI now
ahocorasick
https://pypi.python.org/pypi/ahocorasick/0.9
esmre
https://pypi.python.org/pypi/esmre/0.3.1
But the fact that the packages are all based on DFA
The source code is provided here such as the following:
#!/usr/bin/python2.6#-*-Coding:utf-8-*-ImportTime class Node(object): def __init__(self):Self.children =None # tags match to keywordsSelf.flag =False# The Encode of Word is UTF-8 def add_word(Root,word): ifLen (word) <=0:returnnode = root forIinchRange (len (word)):ifNode.children = =None: Node.children = {} Node.children[word[i]] = node ()elifWord[i] not inchNode.children:node.children[word[i]] = node () node = node.children[word[i]] Node.flag =True def init(word_list):root = Node () forLineinchWord_list:add_word (Root,line)returnRoot# The Encode of Word is UTF-8# The Encode of message is UTF-8 def key_contain(message, root):res = set () forIinchRange (len (message)): p = root J = I while(J<len (message) andp.children!=None andMESSAGE[J]inchP.children):ifP.flag = =True: Res.add (message[i:j]) p = p.children[message[j]] J = j +1 ifp.children==None: Res.add (Message[i:j])#print '---word---', message[i:j] returnRes def DFA(): Print '----------------DFA-----------'Word_list = [' Hello ',' civilian police ',' Friends ',' daughter ',' police station ',' Police station '] Root = init (word_list) message =' everywhere bite barking, frighten home 11-year-old daughter hiding in the house dare not out, until the police arrived in the district police station, the children from the house rescued. Finally, after obtaining the permission of the owner, the police and the villagers joined forces to kill the only Mad Dog.x = Key_contain (message, root) forIteminchX:PrintItemif__name__ = =' __main__ ': DFA ()
Please read my article again.
http://blog.csdn.net/woshiaotian/article/details/10047675
DFA Algorithm for keyword matching