使用Jython从Java代码调用Python时出现错误:ImportError: 没有名为nltk的模块

3 投票
1 回答
1824 浏览
提问于 2025-04-18 07:48

我在用Jython通过PythonInterpreter从Java代码里调用Python代码。这个Python代码的功能就是给句子加标签:

import nltk
import pprint

tokenizer = None
tagger = None   

def tag(sentences):
    global tokenizer
    global tagger
    tagged = nltk.sent_tokenize(sentences.strip())
    tagged = [nltk.word_tokenize(sent) for sent in tagged]
    tagged = [nltk.pos_tag(sent) for sent in tagged]
    return tagged

def PrintToText(tagged):
    output_file = open('/Users/ha/NetBeansProjects/JythonNLTK/src/jythonnltk/output.txt', 'w')
    output_file.writelines( "%s\n" % item for item in tagged )
    output_file.close()  

def main():
    sentences = """What is the salary of Jamie"""  
    tagged = tag(sentences)
    PrintToText(tagged)
    pprint.pprint(tagged)

if __name__ == 'main':    
    main()

我遇到了这个错误:

run:
Traceback (innermost last):
  (no code object) at line 0
  File "/Users/ha/NetBeansProjects/JythonNLTK/src/jythonnltk/Code.py", line 42
        output_file.writelines( "%s\n" % item for item in tagged )
                                              ^
SyntaxError: invalid syntax
BUILD SUCCESSFUL (total time: 1 second)

如果我在Python项目里直接运行这个代码,它是可以正常工作的,但从Java调用时却出现了这个错误。我该怎么解决呢?

提前谢谢你们!

更新
我按照@User的建议,把代码改成了output_file.writelines( ["%s\n" % item for item in tagged] ),但是又收到了另一个错误信息:

Traceback (innermost last):
  File "/Users/ha/NetBeansProjects/JythonNLTK/src/jythonnltk/Code.py", line 5, in ?
ImportError: no module named nltk
BUILD SUCCESSFUL (total time: 1 second)

1 个回答

1

现在编译时的语法错误解决了,但你遇到了运行时错误。什么是 nltk?它在哪里?ImportError 表示 nltk 不在你的导入路径中。

试着写一个简单的小程序,检查一下 sys.path;你可能需要在导入 nltk 之前,把它的路径添加进去。

### The import fails if nltk is not in the system path:
>>> import nltk
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named nltk

### Try inspecting the system path:
>>> import sys
>>> sys.path
['', '/usr/lib/site-python', '/usr/share/jython/Lib', '__classpath__', '__pyclasspath__/', '/usr/share/jython/Lib/site-packages']

### Try appending the location of nltk to the system path:
>>> sys.path.append("/path/to/nltk")

#### Now try the import again.

撰写回答