python第三方库AC自动机pyahocorasick的使用

pyahocorasick是一个快速且内存效率高的库,用于精确或近似多模式字符串搜索,这意味着您可以在某些输入文本中一次找到多个关键字符串出现
字符串“索引”可以提前构建并保存到磁盘以便稍后重新发送。

pyahocorasick是用 C 语言实现的,并在 Python 3.6 及更高版本上进行了测试。它适用于 Linux、maOS 和 Windows。

该模块是用 C 编写的。您需要安装 C 编译器来编译本机 CPython 扩展。

安装:

pip install pyahocorasick

然后创建一个自动机:

>>> import ahocorasick
>>> A = ahocorasick.Automaton()

该项模块可以用作trie,或ac自动机。

1、做为trie树的用法:

您可以将 Automaton 类用作 trie。
将一些字符串键及其关联值添加到此 trie。在这里,我们将(插入索引,原始字符串)的元组作为值关联到我们添加到 trie 的每个键字符串:

1.1 构建trie树

>>> for idx, key in enumerate('he her hers she'.split()):
...   A.add_word(key, (idx, key))

1.2 trie树查询

检查 trie 中是否存在某些字符串:

>>> 'he' in A
True
>>> 'HER' in A
False

2、下面主要介绍ac自动机的用法

创建自动机

A.make_automaton()

2.1 Automaton 类具有以下主要的 Aho-Corasick 方法:

  • make_automaton()
    完成并创建 Aho-Corasick 自动机。

  • iter(string, [start, [end]])
    使用提供的输入执行 Aho-Corasick 搜索过程string。为在字符串中找到的键返回元组 (end_index, value) 的迭代器。

  • iter_long(string, [start, [end]])
    返回搜索最长、非重叠匹配的迭代器(AutomatonSearchIterLong 类的对象)。

2.2 直接看代码

#ac自动机
import ahocorasick as ah

aca= ah.Automaton()
with open('userdict.txt','r',encoding='utf-8')as f2: #加载文件
    keywords = [a.strip() for a in f2.readlines()]    #加载关键词

#利用 add_word方法 将关键词加入自动机!
# 该方法必须包含2个参数,第一个参数是检索词,第二个参数可以任意。
# 此处第二个参数为tuple,作为检索后的返回值,类似(39, '工程总承包') 。第40个词,词为工程总承包。可以自定义。
for x in range(len(keywords)):
    aca.add_word(keywords[x],(x,keywords[x]))

# 创建 Aho-Corasick 自动机
aca.make_automaton()    

with open('jianjie.txt','r',encoding='utf-8')as f: #打开要检索文档
    jianjie=f.read() #读取正文(如果太多,可以分断加载,分段检索)

# 开始查找  
# 该方法 匹配最长的字符串
for item in aca.iter_long(jianjie):
    print(item)
    
print('-'*20)    

# 开始查找
# 该方法 匹配所有字符串
for item in aca.iter(jianjie):
    print(item)

运行结果

(110, (39, '工程总承包'))
(285, (313, '印刷用CTP板基'))
--------------------
(110, (39, '工程总承包'))
(283, (315, 'CTP'))
(285, (313, '印刷用CTP板基'))

3、官网地址

https://pyahocorasick.readthedocs.io/en/latest/#aho-corasick-methods

posted on 2022-04-26 20:50  耀扬  阅读(4734)  评论(0编辑  收藏  举报

导航