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