NameError: name nltk is not defined error typically occurs when we use the “nltk” module without importing it first, or it has not been installed in the environment.
Here are three ways to fix the error:
- Installing the “nltk” module
- Check if you have multiple Python versions installed
- Fixing the error in Visual Studio Code (VSCode)
Common reasons for the error
- NLTK package is not installed.
- NLTJ package is not imported.
- Incorrect import statement
- A typographical error in the import statement
- Conflicting names or overwritten variable
Flowchart
How to fix the error
Solution 1: Install the ‘nltk’ module
To fix the 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.
import nltk
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)
Output
['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: Fixing the error in Visual Studio Code (VSCode)
If you are using a 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.
/path/to/python3
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.