Я использую эту библиотеку 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
}
Я что-то упустил? Я делаю это на больших строках, поэтому постобработка - это не первый вариант. Есть ли способ получить желаемый результат?