Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NLTK - No module named corpus

After installing NLTK and NLTK-DATA with PIP, i run python then i type from nltk.corpus import cmudict and it works. But when i wrote a script like this:

from nltk.corpus import cmudict

d = cmudict.dict()

def nsyl(word):
    return [len(list(y for y in x if y[-1].isdigit())) for x in d[word.lower()]]

print nsyl("hello")

I have the following error :

Traceback (most recent call last):
File "nltk.py", line 1, in <module>
from nltk.corpus import cmudict
File "nltk.py", line 1, in <module>
from nltk.corpus import cmudict
ImportError: No module named corpus

How can i fix this ?

Thanks in advance

like image 753
user35657 Avatar asked Jul 06 '14 02:07

user35657


People also ask

How do I fix No module named NLTK?

The Python "ModuleNotFoundError: No module named 'nltk'" occurs when we forget to install the nltk module before importing it or install it in an incorrect environment. To solve the error, install the module by running the pip install nltk command.

What is NLTK Corpus library in Python?

NLTK is a standard python library with prebuilt functions and utilities for the ease of use and implementation. It is one of the most used libraries for natural language processing and computational linguistics.


2 Answers

From your stacktrace: File "nltk.py", line 1, in <module>, you have called your file nltk.py. When python searches for a module, it looks in the current directory first, and you have "nltk.py" there. It will import this as nltk, and since your code does not define corpus, it can't find nltk.corpus.

To fix this, you should rename your file to something else, say nltkexperience.py. Also make sure to remove "nltk.pyc" from your directory if it exists, since this will also be loaded (it's the byte compiled version of your code). After that, it should work fine.

like image 162
Jonathan Villemaire-Krajden Avatar answered Sep 20 '22 23:09

Jonathan Villemaire-Krajden


As others have pointed out, this seems to be a case of version mismatch. If you have multiple versions of Python installed, make sure that the one where you installed NLTK is the one being used when running the script.

As an example, I have Python 2.7, Python 3.3, and Anaconda Python (2.7) installed. My shell defaults to Anaconda (and its pip, e.g.). So when I install something via pip and run it on the command line, it works. At the same time, my Vim is compiled to use the system's Python, and it doesn't see Anaconda's installs/ libraries. So if from within Vim I run Python, I will get an error that the library I installed is not found.

Hope this helps.

like image 44
Ambidextrous Avatar answered Sep 20 '22 23:09

Ambidextrous