无法导入nltk。说“ImportError:没有名为collocations的模块”

时间:2017-04-22 09:32:04

标签: python python-2.7 pip nltk ubuntu-16.04

我刚刚使用以下命令通过pip安装了nltk:

sudo pip install -U nltk

我也以类似的方式立即安装了numpy,我尝试导入nltk并在终端输入'python'后测试并输入'import nltk',然后我得到了这个:

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

我尝试在线找到解决方案并找到此链接Importing Libraries Issue - "ImportError: No Module named ____", 所以我尝试了这个命令:export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages,但没有任何改变可能是因为找不到模块本身。我也尝试使用命令

sudo pip install -U collocations

但它说

Collecting collocations
  Could not find a version that satisfies the requirement collocations (from versions: )
No matching distribution found for collocations

当我第一次尝试它时也说 您正在使用pip版本8.1.1,但版本9.0.1可用。 您应该考虑通过'pip install --upgrade pip'命令进行升级。

我无法直接升级,但在使用时可以升级: sudo -H pip install --upgrade pip

但我仍然得到同样的东西。我是python的新手,想知道我做错了什么。我最近不得不重新安装Ubuntu 16.04所以我认为操作系统工作正常。非常感谢你

编辑:所以在我的主文件夹中有一个名为nltk.py的文件,可能是影响了这个,我已经删除了文件但是当我尝试导入nltk并打印上面相同的东西时它仍然以某种方式创建追溯.... 该文件的内容是:

import sys
import nltk
from nltk.collocations import *
bigram_measures = nltk.collocations.BigramAssocMeasures()
trigram_measures = nltk.collocations.TrigramAssocMeasures()

# change this to read in your data
finder = BigramCollocationFinder.from_words(
   nltk.corpus.genesis.words('annotation/dataset.txt'))

# only bigrams that appear 3+ times
finder.apply_freq_filter(3) 

# return the 10 n-grams with the highest PMI
finder.nbest(bigram_measures.pmi, 10)

1 个答案:

答案 0 :(得分:0)

请使用virtualenv,因为如果您更新或安装全局python包是不好的,因为例如ubuntu为自己的软件使用一些特殊的软件包版本,如果你改变一些东西,这可能会产生很多问题。您可以使用以下命令安装它:

pip install virtualenv

这是link,其中介绍了如何使用它。

这也可能解决您的问题。我自己用ubuntu 16.04测试了它。