【问题标题】:Is it possible to speed up Wordnet Lemmatizer?是否可以加快 Wordnet Lemmatizer?
【发布时间】:2013-04-17 09:07:25
【问题描述】:

我在 Brown Corpus 上通过 NLTK 使用 Wordnet Lemmatizer(以确定其中的名词更多地以单数形式还是复数形式使用)。
from nltk.stem.wordnet import WordNetLemmatizer
l = WordnetLemmatizer()

我注意到,即使是最简单的查询,例如下面的查询,也需要相当长的时间(至少一两秒)。
l("cats")

大概这是因为每个查询都必须与 Wordnet 建立网络连接?..
我想知道是否有办法仍然使用 Wordnet Lemmatizer 但它的执行速度要快得多?例如,将 Wordnet 下载到我的机器上对我有帮助吗? 或者有什么其他建议?

我正在尝试弄清楚 Wordnet Lemmatizer 是否可以变得更快,而不是尝试不同的 lemmatizer,因为我发现它在 Porter 和 Lancaster 等其他产品中效果最好。

【问题讨论】:

    标签: nltk wordnet lemmatization


    【解决方案1】:

    我用过这样的词形还原器

    from nltk.stem.wordnet import WordNetLemmatizer # to download corpora: python -m    nltk.downloader all
    lmtzr = WordNetLemmatizer() # create a lemmatizer object
    lemma = lmtzr.lemmatize('cats')
    

    在我的机器上一点也不慢。无需连接到网络即可执行此操作。

    【讨论】:

      【解决方案2】:

      它不查询互联网,NLTK 从您的本地机器读取 WordNet。当您运行第一个查询时,NLTK 将 WordNet 从磁盘加载到内存中:

      >>> from time import time
      >>> t=time(); lemmatize('dogs'); print time()-t, 'seconds'
      u'dog'
      3.38199806213 seconds
      >>> t=time(); lemmatize('cats'); print time()-t, 'seconds'
      u'cat'
      0.000236034393311 seconds
      

      如果您必须对数千个短语进行词形还原,这会相当慢。但是,如果您正在执行大量冗余查询,则可以通过缓存函数的结果来获得一些加速:

      from nltk.stem import WordNetLemmatizer
      from functools32 import lru_cache
      wnl = WordNetLemmatizer()
      lemmatize = lru_cache(maxsize=50000)(wnl.lemmatize)
      
      lemmatize('dogs')
      

      【讨论】:

      • 关键是,第一个查询也进行了一些初始化。之后它很快。
      • lru_cache 很棒,但不适用于 Python 2.7:可以考虑使用 repoze.lru (docs.repoze.org/lru) 来实现类似功能。
      • @Vorty 我给出的示例使用了具有 lru_cache 的 Python 3 functools 的反向端口:github.com/MiCHiLU/python-functools32
      • Python 2.7 的 functools 怎么样?
      • 这应该被标记为“已接受”,因为它提供了更多详细信息并提供了加快查询速度的说明。
      猜你喜欢
      • 1970-01-01
      • 2018-10-06
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 2017-07-14
      • 2016-02-10
      • 2020-08-23
      相关资源
      最近更新 更多