【问题标题】:String searching library's outcome - bug or feature or my coding error?字符串搜索库的结果 - 错误或功能或我的编码错误?
【发布时间】: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


    【解决方案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})
    

    【讨论】:

    • +1 谢谢。这与我想要的输出一致。您是否有任何机会将其用于大文本?我的意思是,性能方面。
    • 没有大型语料库的直接经验,抱歉。 PyPi 页面说它释放了 GIL,并包含一个“快速”CPython 实现,但除此之外我不知道。
    • 哦,你也可以试试esmre,从here中挑选出来的。
    • 谢谢。我现在可以测试它们了 :) 感谢您的帮助。
    【解决方案2】:

    我理解 Aho-Corasick 算法的方式以及我实现它的方式会让我同意您的预期输出。看起来您使用的 Python 库有误,或者可能有一个标志,您可以告诉它从某个位置开始为您提供所有匹配项,而不仅仅是从特定位置开始的最长匹配项。

    原论文http://www.win.tue.nl/~watson/2R080/opdracht/p333-aho-corasick.pdf中的例子支持你的理解。

    【讨论】:

    • +1 感谢您提供的信息丰富的回答。我担心可能是这种情况。那个库似乎被大量使用了,所以我只是想知道为什么以前没有人发现它。
    猜你喜欢
    • 2021-10-31
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多