0

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.

Fatemeh Rahimi
  • 458
  • 5
  • 20
  • Would you please describe what you are hoping for the function and nltk.book accomplish for you? What is the task? – Fatemeh Rahimi May 02 '21 at 02:21
  • I am trying to import a "text" and then count the lexical diversity of that particular text. NLTK has several corpora for learning. Thanks for helping! – Navid Asgari May 02 '21 at 20:10

1 Answers1

0

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")
Fatemeh Rahimi
  • 458
  • 5
  • 20