Reputation: 63
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
Upvotes: 6
Views: 10425
Reputation: 1478
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.
Upvotes: 8
Reputation: 820
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.
Upvotes: 1