激活TensorFlow环境后Python版本切换为3.5.2致NLTK不可用,如何解决?
解决TensorFlow环境与NLTK版本冲突问题
我已在Python 3.6.3环境中成功安装NLTK且可正常使用,但需要运行一个同时导入NLTK和TensorFlow的文件,因此必须激活TensorFlow环境。在默认环境中执行命令如下:
HP-250-G5-Notebook-PC:~$ python Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 13 2017, 12:02:49) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import nltk >>>激活TensorFlow环境后,系统自动切换为Python 3.5.2,导致NLTK无法使用。
这个问题本质是conda环境的隔离特性导致的——你在Python3.6.3环境里安装的NLTK只属于该环境,而TensorFlow环境用的是Python3.5.2,这个环境里并没有NLTK依赖,所以会导入失败。给你几个实用的解决思路:
直接在TensorFlow环境中安装NLTK
这是最快速的解决方案,步骤很简单:- 激活你的TensorFlow环境:
conda activate your-tensorflow-env(把your-tensorflow-env替换成你实际的环境名称) - 安装NLTK:
pip install nltk - 如果需要NLTK的语料库,进入Python交互模式后执行
nltk.download(),选择需要的语料包下载即可。
- 激活你的TensorFlow环境:
升级TensorFlow环境的Python版本到3.6.3
如果你希望统一两个环境的Python版本(TensorFlow是支持Python3.6的),可以这么操作:- 激活TensorFlow环境:
conda activate your-tensorflow-env - 升级Python版本:
conda install python=3.6.3 - 重新安装适配Python3.6的TensorFlow版本,比如
pip install tensorflow==1.13.1(这个版本完美兼容Python3.6,你也可以根据需求选择其他兼容版本) - 最后安装NLTK:
pip install nltk
- 激活TensorFlow环境:
创建全新的整合环境
干脆直接搭建一个同时兼容TensorFlow和NLTK的新环境,彻底避免版本冲突:- 创建新环境:
conda create -n tf-nltk-env python=3.6.3 - 激活环境:
conda activate tf-nltk-env - 一次性安装所需依赖:
pip install tensorflow nltk
- 创建新环境:
不管选哪种方法,都能让你在同一个环境里顺畅使用TensorFlow和NLTK啦。
内容的提问来源于stack exchange,提问作者V. Shikongo
相关产品推荐
相关产品推荐

