Ferramenta de teste e correspondência de palavras-chave e substituição de alto desempenho.
É implementado pelo cython e será compilado no cpp. A estrutura de dados do teste é cedro, que é um teste de matriz dupla otimizado. ele suporta Python2.7 e 3.4+. Suporta pickle para despejar e carregar.
Se você achou isso útil, por favor dê uma estrela!
Este módulo está escrito em Cython. Você precisa do Cython instalado.
pip install cyac
Em seguida, crie um teste
>>> from cyac import Trie
>>> trie = Trie()
adicionar/obter/remover palavra-chave
>>> 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
obter todas as palavras-chave
>>> for key, id_ in trie.items():
>>> print(key, id_)
prefixar/prever
>>> # 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_)
tente extrair, substituir
>>> 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)
Extrato de Aho Corasick
>>> ac = AC.build([u"python", u"ruby"])
>>> for id, start, end in ac.match(u"python ruby"):
>>> print(id, start, end)
Exportar para arquivo, então podemos usar o mmap para carregar o arquivo e compartilhar dados entre processos.
>>> ac = AC.build([u"python", u"ruby"])
>>> ac.save("filename")
>>> ac.to_buff(buff_object)
Inicialização do buffer 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
Exemplo de múltiplos processos
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()
Para obter mais informações sobre multiprocessamento e análise de memória no cyac, consulte este problema.
A função "match" do autômato AC é segura para thread/processo. É possível encontrar correspondências em paralelo com um autômato AC compartilhado, mas não escrever/anexar padrões a ele.
No Ubuntu 14.04.5/Intel(R) Core(TM) CPU i7-4790K @ 4,00GHz.
Comparado com HatTrie, o eixo Horizon é um token num. O eixo vertical é usado no tempo (segundos).
Comparado com flashText. A expressão regular é muito lenta nesta tarefa (consulte o benchmark do flashText). O eixo do horizonte é o char num para corresponder. O eixo vertical é usado no tempo (segundos).
Comparado com pyahocorasick, o eixo Horizon é char num para ser compatível. O eixo vertical é usado no tempo (segundos).
>>> len(char.lower()) == len(char) # this is always true in python2, but not in python3
>>> len(u"İstanbul") != len(u"İstanbul".lower()) # in python3
No caso de correspondência insensível a maiúsculas e minúsculas, esta biblioteca cuida do fato e retorna o deslocamento correto.
python setup.py build
PYTHONPATH= $( pwd ) /build/BUILD_DST python3 tests/test_all.py
PYTHONPATH= $( pwd ) /build/BUILD_DST python3 bench/bench_ * .py