【问题标题】:Using nltk.book import in a function在函数中使用 nltk.book 导入
【发布时间】:2021-07-24 20:56:45
【问题描述】:

我正在尝试编写一个简单的函数如下:

def lexical_diversity(text,word):
    from nltk.book import text
    return 100*text.count(word)/len(set(text))

我知道我可以在函数之前导入文本。但是,我想知道为什么会出现以下错误

ImportError: cannot import name 'text' from 'nltk.book'

它告诉我,作为语料库的“文本”在 nltk 中不存在——这是真的。但是,我希望用户将文本识别为 text1、text2 或 text3。

【问题讨论】:

  • 您能否描述一下您希望该功能和 nltk.book 为您完成什么?任务是什么?
  • 我正在尝试导入“文本”,然后计算该特定文本的词汇多样性。 NLTK 有几个用于学习的语料库。感谢您的帮助!

标签: python function nlp nltk nltk-book


【解决方案1】:

要在python中导入库的子模块,可以使用importlib模块。

import importlib

def lexical_diversity(nltk_sub_module,word):
    
    imported_model_module = importlib.import_module( "nltk.book")
    text = getattr(imported_model_module,nltk_sub_module)

    return 100*text.count(word)/len(set(text))

lexical_diversity("text3", "book")

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-03
  • 1970-01-01
  • 2011-09-27
  • 2021-06-10
  • 2020-10-26
  • 2021-10-10
  • 1970-01-01
相关资源
最近更新 更多