繁体   English   中英

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

[英]Call Python from Java code using Jython cause error: ImportError: no module named 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( "%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中调用它会发生此错误,这段代码工作得很好。 我该如何解决?

提前致谢

更新 :我已经将行编辑为output_file.writelines( ["%s\\n" % 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)

现在编译时语法错误已解决,您将遇到运行时错误。 什么是nltk 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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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