Using nltk.book import in a function

201 Views Asked by At

I am trying to write a simple function as follows:

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. But, I was wondering why I get the following error

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

It is telling me that "text" as a corpus does not exist in nltk--it is true. But, I want the user to identify the text to be text1, text2, or text3.

1

There are 1 best solutions below

1
On

In order to import a submodule of a library in python, you can use importlib module.

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")