Wed Apr 20 2022·1 min read
Photo by Andre Benz
The Python "NameError: name 'nltk' is not defined" occurs when we use the
nltk module without importing it first. To solve the error, install the module
and import it (
import nltk) before using it.
Open your terminal in your project's root directory and install the
# 👇️ in a virtual environment or using Python 2 pip install nltk # 👇️ for python 3 (could also be pip3.10 depending on your version) pip3 install nltk # 👇️ if you get permissions error sudo pip3 install nltk # 👇️ if you don't have pip in your PATH environment variable python -m pip install nltk # 👇️ for python 3 (could also be pip3.10 depending on your version) python3 -m pip install nltk # 👇️ for Anaconda conda install -c anaconda nltk
After you install the nltk module, make sure to import it before using it.
# ✅ import nltk first import nltk # 👇️ download nltk libraries if necessary nltk.download() sentence = """At eight o'clock on Thursday morning Arthur didn't feel very good.""" tokens = nltk.word_tokenize(sentence) print(tokens)
You can remove the
nltk.download() line if you don't have to download any
Make sure you haven't misspelled the module you are importing because module names are case-sensitive.
Also, make sure you haven't imported from
nltk in a nested scope, e.g. a
function. Import the module at the top level to be able to use it throughout