I am using this python library that implements the Aho-Corasick string searching algorithm that finds a set of patterns in a given string in one pass. The output is not what I am expecting:
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 output I was expecting was this:
{
'the first sentence': 3,
'the first sentence is': 2,
'first sentence': 3,
'first sentence is': 2
}
Am I missing something? I am doing this on large strings so post processing is not my first option. Is there a way to get the desired output?