NameError: name 'nltk' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

NameError: name 'nltk' is not defined in Python #

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.

nameerror name nltk is not defined

Open your terminal in your project's root directory and install the nltk module.

shell
# 👇️ 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.

main.py
# ✅ 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 nltk-related libraries.

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 your code.

Conclusion #

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.