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



我正在通过PythonInterpreter使用jython从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( "%sn" % 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( "%sn" % item for item in tagged )
                                              ^
SyntaxError: invalid syntax
BUILD SUCCESSFUL (total time: 1 second)

如果我在python项目中打开它,但从java调用它会引发此错误,那么这段代码运行得很好。我该如何解决?

提前感谢

更新:我已经将output_file.writelines( ["%sn" % item for item in tagged] )的行编辑为@User sugeested,但我收到了另一条错误消息:

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)

现在编译时语法错误已经解决,您将得到运行时错误。什么是nltknltk在哪里?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.

相关内容

  • 没有找到相关文章

最新更新