고성능 Trie & 키워드 일치 및 교체 도구.
cython으로 구현되었으며 cpp로 컴파일됩니다. trie 데이터 구조는 최적화된 이중 배열 트라이인 cedar입니다. Python2.7 및 3.4+를 지원합니다. 덤프 및 로드를 위한 피클을 지원합니다.
이 내용이 유용하다고 생각되면 별점을 주세요!
이 모듈은 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 자동화의 "일치" 기능은 스레드/프로세스로부터 안전합니다. 공유 AC 자동 장치와 병렬로 일치하는 항목을 찾을 수 있지만 패턴을 쓰거나 추가할 수는 없습니다.
Ubuntu 14.04.5/Intel(R) Core(TM) i7-4790K CPU @ 4.00GHz.
HatTrie와 비교하면 Horizon 축은 토큰 번호입니다. 세로축은 사용시간(초)입니다.
flashText와 비교. 이 작업에서는 정규 표현식이 너무 느립니다(flashText의 벤치마크 참조). 수평 축은 일치할 문자 번호입니다. 세로축은 사용시간(초)입니다.
pyahocorasick과 비교할 때 Horizon 축은 일치하는 문자 번호입니다. 세로축은 사용시간(초)입니다.
>>> 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