Python is one of the easiest programming languages for beginners to learn. It’s also popular among experienced programmers for being easy to work with, powerful enough for just about everything and having pretty decent library support.
That said, random bugs and glitches keep popping up from time to time. In this article, we’re talking about the “namerror: name nltk is not defined” error in Python, what causes it and how to fix the problem.
What causes the error?
The ‘nameerror’ message often pops up when you’re trying to import a library that you haven’t installed yet. In this case, the library in question is nltk. The error indicates either an incomplete or missing installation or improper reference in your script.
Keep in mind that before you use any external libraries or objects in Python, you need to install and import them into your script.
How to fix this?
Depending on where you’ve made a mistake in your script, there are two solutions to the problem.
Use pip to install nltk
If you’ve not installed nltk, or simply downloaded the wheel package to your project’s local directory, you won’t be able to use the library. While you can install it manually using a wheel file, it’s best to use pip for the task.
All you have to do is open a terminal, head over to the root directory of your project and run the following command.
sudo pip3 install nltk
If you’re using Anaconda instead, run this command.
conda install -c anaconda nltk
Make sure to import nltk before usage
Another common mistake that beginners often do is forgetting to import the library before using it in their scripts. Before you make any references to nltk, you need to import it as follows:
An important thing to keep in mind is to spell the package correctly and be vary of its case. A typo or case-sensitivity mistake can also cause this error.