简体   繁体   English

在 function 中使用 nltk.book 导入

[英]Using nltk.book import in a function

I am trying to write a simple function as follows:我正在尝试编写一个简单的 function 如下:

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

I understand that I can import a text before the function.我知道我可以在 function 之前导入文本。 But, I was wondering why I get the following error但是,我想知道为什么会出现以下错误

ImportError: cannot import name 'text' from 'nltk.book' ImportError:无法从“nltk.book”导入名称“文本”

It is telling me that "text" as a corpus does not exist in nltk--it is true.它告诉我,作为语料库的“文本”在 nltk 中不存在——这是真的。 But, I want the user to identify the text to be text1, text2, or text3.但是,我希望用户将文本识别为 text1、text2 或 text3。

In order to import a submodule of a library in python, you can use importlib module.为了在 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM