Call Python from Java code using Jython cause erro

2019-07-04 02:42发布

问题:

I'm calling a python code from a java code using jython by PythonInterpreter. the python code just tag the sentence:

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()

I got this error:

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)

this code works very fine if I opened it in a python project but calling it from java fire this error. How can I solve it?

Thanks in advance

UPDATE: I have edit the line to output_file.writelines( ["%s\n" % item for item in tagged] ) as @User sugeested but I received another error message:

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:

Now that the compile-time syntax error is solved, you are getting run-time errors. What is nltk? Where is nltk? The ImportError implies that nltk is not in your import path.

Try writing a small simple program and examine sys.path ; you might need to append location of nltk before importing it.

### 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.