pyahocorasick使用(ac自动机)

一、简介

pyahocorasick是一个快速高效的库,用于精确或近似的多模式字符串搜索,这意味着您可以在一些输入文本中同时找到多个关键字字符串。字符串“索引”可以提前构建,并保存(作为pickle)到磁盘,以便以后重新使用。该库提供了一个ahocarasick Python模块,您可以将其用作Trie之类的普通dict,或者将Trie转换为自动机,以实现高效的Aho-Carasick搜索。

二、安装
pip install pyahocorasick
三、使用
1.新建自动机

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

import ahocorasick
A = ahocorasick.Automaton()
for idx, key in enumerate('he her hers she'.split()):
    A.add_word(key, (idx, key))

然后可以检查某些字符串是否在trie当中

'he' in A
Out[5]: True
'HE' in A
Out[6]: False
A.get('he')
Out[7]: (0, 'he')
A.get('cat', 'not exists')
Out[8]: 'not exists'
A.get('dog')
Traceback (most recent call last):
  File "/Users/daxu/.conda/envs/py38/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3441, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-9-6421fd467385>", line 1, in <module>
    A.get('dog')
KeyError
2.将trie转换为ac自动机,启动Aho Corasick搜索
A.make_automaton()
3. 在输入字符串中搜索所有出现的键

在这里,我们打印结果并检查它们是否正确。Automaton.iter()方法将找到的元素的结束索引,以及具体值作为元组,按照插入顺序返回。

test_str = 'hh he her hers she whos'
for end_index, (insert_order, original_value) in A.iter(test_str):
    start_index = end_index - len(original_value) + 1
    print((start_index, end_index, (insert_order, original_value)))
    assert test_str[start_index:start_index + len(original_value)] == original_value
    
(3, 4, (0, 'he'))
(6, 7, (0, 'he'))
(6, 8, (1, 'her'))
(10, 11, (0, 'he'))
(10, 12, (1, 'her'))
(10, 13, (2, 'hers'))
(15, 17, (3, 'she'))
(16, 17, (0, 'he'))

参考:https://pyahocorasick.readthedocs.io/en/latest/
暂时完结。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值