【发布时间】:2011-12-27 08:46:36
【问题描述】:
我正在使用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
}
我错过了什么吗?我在大字符串上这样做,所以后处理不是我的第一选择。有没有办法获得所需的输出?
【问题讨论】:
标签: python string algorithm search text