AC自动机
Aho-Corasick automaton,该算法在1975年产生于贝尔实验室,是著名的多模匹配算法。其主要是将关键词存储在树形结构里面,通过设置状态控制关键词的匹配
AC自动机代码(python)
class Node(object):
"""节点类"""
def __init__(self, char=""):
self.children = dict()
self.char = char
self.word = ""
self.fail = None
self.tail = None
class AC_Automata(object):
"""ac 自动机"""
def __init__(self):
self.root = Node()
def build_tree(self, key_words):
"""构建字典树"""
for word in key_words:
temp_node = self.root
for char in word:
if char not in temp_node.children:
temp_node.children[char] = Node()
temp_node = temp_node.children[char]
temp_node.word = word
def build_ac(self):
"""构建ac自动机"""
queue_list = list()
queue_list.insert(0, self.root)
while len(queue_list) > 0:
temp_node = queue_list.pop()
for char, children in temp_node.children.items():
if temp_node == self.root:
children.fail = self.root
else:
children.fail = temp_node.fail.children.get(char) or self.root
if children.fail:
children.tail = children.fail if children.fail.word else children.fail.tail
queue_list.insert(0, children)
def search(self, content):
temp_node = self.root
for index, char in enumerate(content):
while temp_node and char not in temp_node.children:
temp_node = temp_node.fail
temp_node = temp_node.children.get(char) if temp_node is not None else self.root
if temp_node.word:
yield ((index+1 - len(temp_node.word), index+1), temp_node.word)
tail_node = temp_node.tail
while tail_node:
yield ((index+1 - len(tail_node.word), index+1), tail_node.word)
tail_node = tail_node.tail
if __name__ == '__main__':
key_words = 'AC,演示,自动机'.split(',')
ac = AC_Automata()
ac.build_tree(key_words)
ac.build_ac()
string = "这是AC自动机演示代码,现在正在演示"
a = ac.search(string)
for i in a:
print(i)
运行结果如下所示:

本文介绍了AC自动机(Aho-Corasick算法)的基本原理和Python实现。AC自动机是一种用于多模式匹配的算法,可以快速查找文本中是否存在多个关键词。通过构建字典树和失败指针,AC自动机能够在一次遍历中找到所有匹配的关键词。示例代码展示了如何构建AC自动机并应用于实际字符串搜索,提高了搜索效率。

705

被折叠的 条评论
为什么被折叠?



