快速 n 元语法计算
我正在使用 NLTK 在语料库中搜索 n-gram,但在某些情况下需要很长时间。我注意到计算 n 元语法在其他软件包中并不是一个不常见的功能(显然 Haystack 有一些功能)。这是否意味着如果我放弃 NLTK,可能会有一种更快的方法在我的语料库中查找 n 元语法?如果是这样,我可以用什么来加快速度?
I'm using NLTK to search for n-grams in a corpus but it's taking a very long time in some cases. I've noticed calculating n-grams isn't an uncommon feature in other packages (apparently Haystack has some functionality for it). Does this mean there's a potentially faster way of finding n-grams in my corpus if I abandon NLTK? If so, what can I use to speed things up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您没有指出是否需要单词级 n 元语法或字符级 n 元语法,因此我将假设前者,而不失一般性。
我还假设您从一个由字符串表示的标记列表开始。您可以轻松地做的是自己编写 n 元语法提取。
然后将
yield
替换为您想要对每个 n-gram 采取的实际操作(将其添加到dict
,将其存储在数据库中,等等)以摆脱发电机开销。最后,如果确实不够快,请将上面的内容转换为 Cython 并编译。使用
defaultdict
而不是yield
的示例:Since you didn't indicate whether you want word or character-level n-grams, I'm just going to assume the former, without loss of generality.
I also assume you start with a list of tokens, represented by strings. What you can easily do is write n-gram extraction yourself.
Then replace the
yield
with the actual action you want to take on each n-gram (add it to adict
, store it in a database, whatever) to get rid of the generator overhead.Finally, if it's really not fast enough, convert the above to Cython and compile it. Example using a
defaultdict
instead ofyield
:您可能会发现使用
zip
和 splat (*) 运算符 这里:You might find a pythonic, elegant and fast ngram generation function using
zip
and splat (*) operator here :对于字符级 n-gram,您可以使用以下函数
For character-level n-grams you could use the following function