cyac
1.0.0
高性能 Trie 和关键字匹配和替换工具。
它由cython实现,并将编译为cpp。 trie数据结构是cedar,它是一种优化的双数组trie。它支持Python2.7和3.4+。它支持pickle转储和加载。
如果您觉得有用请给个star!
该模块是用 cython 编写的。您需要安装 cython。
pip install cyac
然后创建一个Trie树
>>> from cyac import Trie
>>> trie = Trie()
添加/获取/删除关键字
>>> trie.insert(u"哈哈") # return keyword id in trie, return -1 if doesn't exist
>>> trie.get(u"哈哈") # return keyword id in trie, return -1 if doesn't exist
>>> trie.remove(u"呵呵") # return keyword in trie
>>> trie[id] # return the word corresponding to the id
>>> trie[u"呵呵"] # similar to get but it will raise exeption if doesn't exist
>>> u"呵呵" in trie # test if the keyword is in trie
获取所有关键词
>>> for key, id_ in trie.items():
>>> print(key, id_)
前缀/预测
>>> # return the string in the trie which starts with given string
>>> for id_ in trie.predict(u"呵呵"):
>>> print(id_)
>>> # return the prefix of given string which is in the trie.
>>> for id_, len_ in trie.prefix(u"呵呵"):
>>> print(id_, len_)
特里提取,替换
>>> python_id = trie.insert(u"python")
>>> trie.replace_longest("python", {python_id: u"hahah"}, set([ord(" ")])) # the second parameter is seperator. If you specify seperators. it only matches strings tween seperators. e.g. It won't match 'apython'
>>> for id_, start, end in trie.match_longest(u"python", set([ord(" ")])):
>>> print(id_, start, end)
阿霍科拉西克提取物
>>> ac = AC.build([u"python", u"ruby"])
>>> for id, start, end in ac.match(u"python ruby"):
>>> print(id, start, end)
导出到文件,然后我们可以使用mmap加载文件,在进程之间共享数据。
>>> ac = AC.build([u"python", u"ruby"])
>>> ac.save("filename")
>>> ac.to_buff(buff_object)
从 Python 缓冲区初始化
>>> import mmap
>>> with open("filename", "r+b") as bf:
buff_object = mmap.mmap(bf.fileno(), 0)
>>> AC.from_buff(buff_object, copy=True) # it allocs new memory
>>> AC.from_buff(buff_object, copy=False) # it shares memory
多进程示例
import mmap
from multiprocessing import Process
from cyac import AC
def get_mmap():
with open("random_data", "r+b") as bf:
buff_object = mmap.mmap(bf.fileno(), 0)
ac_trie = AC.from_buff(buff_object, copy=False)
# Do your aho searches here. "match" function is process safe.
processes_list = list()
for x in range(0, 6):
p = Process(
target=get_mmap,
)
p.start()
processes_list.append(p)
for p in processes_list:
p.join()
有关 cyac 中的多处理和内存分析的更多信息,请参阅此问题。
AC 自动机的“match”功能是线程/进程安全的。可以与共享 AC 自动机并行查找匹配,但不能向其写入/附加模式。
在 Ubuntu 14.04.5/Intel(R) Core(TM) i7-4790K CPU @ 4.00GHz 上。
与HatTrie相比,水平轴是token num。纵轴是使用时间(秒)。
与 flashText 相比。正则表达式在此任务中太慢(请参阅 flashText 的基准测试)。水平轴是要匹配的字符数。纵轴是使用时间(秒)。
与pyahocorasick相比,Horizon轴是要匹配的char num。纵轴是使用时间(秒)。
>>> len(char.lower()) == len(char) # this is always true in python2, but not in python3
>>> len(u"İstanbul") != len(u"İstanbul".lower()) # in python3
在不区分大小写的匹配中,该库会处理这一事实,并返回正确的偏移量。
python setup.py build
PYTHONPATH= $( pwd ) /build/BUILD_DST python3 tests/test_all.py
PYTHONPATH= $( pwd ) /build/BUILD_DST python3 bench/bench_ * .py