我正在使用this python库来实现Aho-Corasick字符串搜索算法,该算法在一次传递中找到给定字符串中的一组模式。输出不是我所期望的:
In [4]: import ahocorasick
In [5]: import collections
In [6]: tree = ahocorasick.KeywordTree()
In [7]: ss = "this is the first sentence in this book the first sentence is really the most interesting the first sentence is always first"
In [8]: words = ["first sentence is", "first sentence", "the first sentence", "the first sentence is"]
In [9]: for w in words:
...: tree.add(w)
...:
In [10]: tree.make()
In [13]: final = collections.defaultdict(int)
In [15]: for match in tree.findall(ss, allow_overlaps=True):
....: final[ss[match[0]:match[1]]] += 1
....:
In [16]: final
{ 'the first sentence': 3, 'the first sentence is': 2}
我期待的输出是:
{
'the first sentence': 3,
'the first sentence is': 2,
'first sentence': 3,
'first sentence is': 2
}
我错过了什么吗?我在大字符串上这样做,所以后期处理不是我的第一选择。有没有办法获得所需的输出?
答案 0 :(得分:1)
我理解Aho-Corasick算法的方式以及我实现它的方式会让我同意你的预期输出。它看起来像你正在使用的Python库是错误的,或者可能有一个标志,你可以告诉它给你从一个位置开始的所有匹配,而不是从特定位置开始的最长匹配。
原始论文http://www.win.tue.nl/~watson/2R080/opdracht/p333-aho-corasick.pdf中的示例支持您的理解。
答案 1 :(得分:1)
我不知道ahocorasick
模块,但这些结果似乎令人怀疑。 acora模块显示了这一点:
import acora
import collections
ss = "this is the first sentence in this book "
"the first sentence is really the most interesting "
"the first sentence is always first"
words = ["first sentence is",
"first sentence",
"the first sentence",
"the first sentence is"]
tree = acora.AcoraBuilder(*words).build()
for match in tree.findall(ss):
result[match] += 1
结果:
>>> result
defaultdict(<type 'int'>,
{'the first sentence' : 3,
'first sentence' : 3,
'first sentence is' : 2,
'the first sentence is': 2})