简体   繁体   中英

Error: No Module Named NLTK Python2.7 Linux

I'm on a Linux Red Hat server and I'm trying to launch a python script. I installed nltk, but when I start my script I get the following error:

ImportError: No module named nltk

Here are my other python installations:

[~/Documents] >which python python2 python3
/bin/python
/bin/python2

However, nltk is installed on:

/usr/lib/python2.7/site-packages

I don't want to change my path variable because I'm not the only one using this server, is there anything else I can do to overcome this problem? Where should I install nltk?

Thanks!

EDIT:

I added NLTK with sudo pip install nltk

[~/Documents] >which pip pip2 pip3
/bin/pip
/bin/pip2
pip3: Command not found.

My path:

[~/Documents] >echo $PATH         

/usr/local/java/java/bin:/bin:/usr/bin:

$PYTHONPATH does not exist, I can't install it using only pip

For the permission I think only root can read/write the nltk files:

ls -l 
drwxr-x---. 23 root root   4096 Nov 23 12:24 nltk
drwxr-x---.  2 root root   4096 Nov 23 12:24 nltk-3.2.1-py2.7.egg-info

You can add to the begin of you python script

import sys; sys.path.append('/usr/lib/python2.7/site-packages')

Edit 1:

this must solve if above does not works:

import sys
sys.path.insert(0, '/usr/lib/python2.7/site-packages')

Edit 2:

change the path in linux for only when script runs

from subprocess import call
call('export PYTHONPATH='/usr/lib/python2.7/':$PYTHONPATH,shell=True)

or you can call the module direct

<nltk.pth>
/usr/lib/python2.7/dist-packages

any python modules or packages in the directory will now be importable.

EDIT 3:

Well after some research maybe there is another way

first of all you need to append the directory to yout path with

import sys; sys.path.append('/usr/lib/python2.7/site-packages')

you will need importlib

from  importlib import import_module

Then you may import your module like this:

mod = import_module('nltk')

to get submodules you may do this:

module_you_want = getattr(mod,'module_you_want')

thats it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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