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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With