栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pyahocorasick使用(ac自动机)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 "", line 1, in 
    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/
暂时完结。。。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/769846.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号