The NameError: name nltk is not defined error typically occurs in Python when we use the “nltk” module without importing it first or it has not been installed in the environment.
How to fix the NameError: name nltk is not defined
Solution 1: Install the ‘nltk’ module
To fix the NameError: name nltk is not defined error, install the “nltk” module using this command: pip install nltk. If you are using Python3, you can use this command: python3 -m pip install nltk.
After installing, you can import it into your Python script.
Let’s write a simple program that tokenizes the simple text.
import nltk nltk.download('punkt') text = "14th Jan is Uttrayan!" tokens = nltk.word_tokenize(text) print(tokens)
['14th', 'Jan', 'is', 'Uttrayan', '!']
In the above code, we will import the NLTK library and then download the ‘punkt’ package, a pre-trained tokenizer for NLTK.
The nltk package is needed to use the word_tokenize() function, which breaks a sentence into individual words or tokens.
Solution 2: Check if you have multiple Python versions installed
You can check this by running the
which -a python and
which -a python3 commands from the terminal:
which -a python /usr/local/bin/python which -a python3 /usr/local/bin/python3 /usr/bin/python3
Solution 3: No module named nltk in Visual Studio Code (VSCode)
If you are using VSCode integrated terminal to run your code, you might get this error even when nltk is already installed. This means the Python and pip versions VSCode uses differ from the one where you install nltk.
import sys print(sys.executable)
It will print output and show the absolute path to the Python used by VSCode.
Copy the path shown in the terminal and add -m pip install nltk as follows:
/path/to/python3 -m pip install nltk
The above command will install nltk for the Python interpreter used by VSCode.