我正在使用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)
答案 0 :(得分:1)
现在解决了编译时语法错误,您将遇到运行时错误。什么是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.