【问题标题】:Unable to import nltk on mac os x无法在 mac os x 上导入 nltk
【发布时间】:2016-07-03 21:12:33
【问题描述】:

我已经成功安装了 nltk from this site。只是为了验证我能够从终端导入它。但是当我从 Spyder 执行我的 python 脚本时,它会在 Spyders 终端中出现以下错误

File "/Prateek/Python/RC_ISSUES/algorithm_RC.py", line 9, in <module>
import nltk

ImportError: No module named nltk

以下输出来自终端

我知道可能会有类似的问题,但我认为它与其他问题不同

【问题讨论】:

  • 您是否检查过 spyders 使用的 python 与您从命令行调用的 python 相同?也许它有它自己的,或者需要指向系统python。
  • 我是python的初学者,请问如何检查它是否指向系统python?。
  • algorithm_RC.py中的import nltk之前将这一行:import sys; print sys.version添加到您的代码中
  • @alvas,它显示2.7.10 (default, Jun 1 2015, 09:45:55) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
  • 瞧,不同的版本,一个在 Oct 23 2015 上编译,另一个在 Jun 1 2015 =)

标签: python macos python-2.7 nltk spyder


【解决方案1】:

当你执行一个 python 脚本时,操作系统正在寻找脚本第一行指定的解释器,大部分时间是:

#!/usr/bin/python

在 Mac OS X 上,这是安装时随系统分发的 python,它是随系统分发的。它通常很可能是编译日期较早的那个:

2.7.10 (default, Jun 1 2015, 09:45:55) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]

如果您在 shell 中执行 type python,您很可能会看到该解释器的另一条路径,例如如果你安装了 brew 版本的 python:

% type python
python is /usr/local/bin/python

所以你有两种解决方法,要么用 python 显式启动你的脚本:

python algorithm_RC.py

如有疑问,请使用您在type 中找到的完整路径:

/usr/local/bin/python algorithm_RC.py

或者,您可以更改脚本的第一行:

#!/usr/bin/env python

它将使用与您从 shell 中获取的相同的 python。您还可以通过以下方式使用手动安装的 python 的完整路径:

#!/usr/local/bin/python

type 命令给出的任何内容。但我建议您不要这样做,因为/usr/bin/env 解决方案更灵活,并确保您在两种情况下都使用来自 shell 和脚本中的相同 python。

最后,你也可以通过从/usr/bin显式调用easy_install来使用系统的python:

sudo /usr/bin/pip nltk

如果你那里没有 pip,那么你必须先安装它:

sudo /usr/bin/easy_install pip

HTH

【讨论】:

  • 感谢您的意见。但我想在 spyder 中运行。这样调试脚本会非常有用
【解决方案2】:

尝试1:

>>>import nltk 

然后回车,现在试试

>>>nltk.download()

【讨论】:

    猜你喜欢
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 2016-05-19
    • 2016-02-12
    • 2013-09-14
    • 1970-01-01
    • 2013-01-28
    相关资源
    最近更新 更多