我一直试图让Stanford POS Tagger工作一段时间。从old SO post我发现了以下(略微修改过的)代码:
stanford_dir = 'C:/Users/.../stanford-postagger-2017-06-09/'
from nltk.tag import StanfordPOSTagger
#from nltk.tag.stanford import StanfordPOSTagger # I tried it both ways
from nltk import word_tokenize
# Add the jar and model via their path (instead of setting environment variables):
jar = stanford_dir + 'stanford-postagger.jar'
model = stanford_dir + 'models/english-left3words-distsim.tagger'
pos_tagger = StanfordPOSTagger(model, jar, encoding='utf8')
text = pos_tagger.tag(word_tokenize("What's the airspeed of an unladen swallow ?"))
print(text)
但是,我收到以下错误:
LookupError:
===========================================================================
NLTK was unable to find the java file!
Use software specific configuration paramaters or set the JAVAHOME environment variable.
===========================================================================
我不知道它在说什么java文件。我确定它找到了正确的文件,因为如果我将路径改为不正确的地方,我会得到一个不同的错误:
LookupError: Could not find stanford-postagger.jar jar file at C:/Users/.../stanford-postagger-2017-06-09/sstanford-postagger.jar
缺少什么java文件?如何让Stanford POS标签器工作?
编辑:
我去了link for Stanford NLP on Windows并尝试了:
(第二次编辑 - 添加安装程序):
import urllib.request
import zipfile
urllib.request.urlretrieve(r'http://nlp.stanford.edu/software/stanford-postagger-full-2015-04-20.zip', r'C:/Users/HMISYS/Downloads/stanford-postagger-full-2015-04-20.zip')
zfile = zipfile.ZipFile(r'C:/Users/HMISYS/Downloads/stanford-postagger-full-2015-04-20.zip')
zfile.extractall(r'C:/Users/HMISYS/Downloads/')
# End second edit
from nltk.tag.stanford import StanfordPOSTagger
# Trying on an older version
_model_filename = r'C:/Users/HMISYS/Downloads/stanford-postagger-full-2015-04-20/models/english-bidirectional-distsim.tagger'
_path_to_jar = r'C:/Users/HMISYS/Downloads/stanford-postagger-full-2015-04-20/stanford-postagger.jar'
st = StanfordPOSTagger(model_filename=_model_filename, path_to_jar=_path_to_jar)
text = st.tag(nltk.word_tokenize("What's the airspeed of an unladen swallow ?"))
print(text)
但我得到了同样的错误。基于this post我使用以下内容设置路径变量:
set STANFORDTOOLSDIR=$HOME
set CLASSPATH=$STANFORDTOOLSDIR/stanford-postagger-full-2015-04-20/stanford-postagger.jar
set export STANFORD_MODELS=$STANFORDTOOLSDIR/stanford-postagger-full-2015-04-20/models
但是我收到了这个错误:
NLTK was unable to find stanford-postagger.jar! Set the CLASSPATH environment variable.
答案 0 :(得分:6)
我在代码中添加了以下几行,并且有效:
import os
java_path = "C:/Program Files/Java/jdk1.8.0_161/bin/java.exe"
os.environ['JAVAHOME'] = java_path