一、简介
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/
暂时完结。。。