简体   繁体   English

NLTK - 没有名为语料库的模块

[英]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. 用PIP安装NLTK和NLTK-DATA之后,我运行python然后从nltk.corpus import cmudict输入它就可以了。 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 提前致谢

From your stacktrace: File "nltk.py", line 1, in <module> , you have called your file nltk.py. 从你的stacktrace: File "nltk.py", line 1, in <module> ,你已经调用了你的文件nltk.py. When python searches for a module, it looks in the current directory first, and you have "nltk.py" there. 当python搜索模块时,它首先查看当前目录,然后你有“nltk.py”。 It will import this as nltk, and since your code does not define corpus, it can't find nltk.corpus . 它会将其导入为nltk,并且由于您的代码未定义语料库,因此无法找到nltk.corpus

To fix this, you should rename your file to something else, say nltkexperience.py . 要解决此问题,您应该将文件重命名为其他内容,例如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). 还要确保从目录中删除“nltk.pyc”(如果存在),因为这也将被加载(它是代码的字节编译版本)。 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. 如果安装了多个版本的Python,请确保安装NLTK的版本是运行脚本时使用的版本。

As an example, I have Python 2.7, Python 3.3, and Anaconda Python (2.7) installed. 例如,我安装了Python 2.7,Python 3.3和Anaconda Python(2.7)。 My shell defaults to Anaconda (and its pip, eg). 我的shell默认为Anaconda(及其pip,例如)。 So when I install something via pip and run it on the command line, it works. 因此,当我通过pip安装并在命令行上运行它时,它可以工作。 At the same time, my Vim is compiled to use the system's Python, and it doesn't see Anaconda's installs/ libraries. 与此同时,我的Vim被编译为使用系统的Python,并没有看到Anaconda的安装/库。 So if from within Vim I run Python, I will get an error that the library I installed is not found. 因此,如果从Vim内部运行Python,我将收到一个错误,我找不到我安装的库。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM