gpt4 book ai didi

java - 使用 Jython 从 Java 代码调用 Python 导致错误 : ImportError: no module named nltk

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:04:19 60 4
gpt4 key购买 nike

我正在通过 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.

关于java - 使用 Jython 从 Java 代码调用 Python 导致错误 : ImportError: no module named nltk,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23909210/

60 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com