python ac自动机

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

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

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)

运行结果如下所示:
在这里插入图片描述

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值