How to Fix NameError: name ‘nltk’ is not defined

Diagram of How to Fix NameError: name 'nltk' is not defined


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.

import nltk

Let’s write a simple program that tokenizes the simple text.

import nltk'punkt')

text = "14th Jan is Uttrayan!"

tokens = nltk.word_tokenize(text)



['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

which -a 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


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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.