首先,我在 MacBook 上使用 Eclipse 进行 Java 编码。我编写了一个使用 NLTK“进行自然语言处理”的 Python 代码,它运行良好。我尝试从 Java 调用一个简单的 Python 代码,它也按预期工作。
但是当我尝试调用使用 NLTK 的 Python 代码时,导入语句失败: “ImportError: No module named nltk”
似乎 Python 能够找到 NLTK 库,但在 Java 中却不能。
我试图在 Python 代码和 Java 代码中都有 import 语句,但没有运气。
这是Python代码:
#!/usr/local/bin/python
# coding: UTF-8
import os, sys
from nltk.tokenize import word_tokenize # Tokenizer
class RTE:
def WordPhraseRate(self, Text):
T_tokens = word_tokenize(Text)
.
.
.
这是Java代码:
import org.python.util.*;
import org.python.core.*;
import org.python.util.PythonInterpreter;
public class NLU_RTE
{
public PythonInterpreter interpreter = null;
public NLU_RTE()
{
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
this.interpreter = new PythonInterpreter();
}
void execfile( final String fileName )
{
this.interpreter.execfile(fileName);
}
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
public static void main( String gargs[] )
{
NLU_RTE ie = new NLU_RTE();
ie.execfile("/Users/Desktop/nlu.py");
ie.interpreter.exec("from nltk.tokenize import word_tokenize # Tokenizer");
String T="About two weeks before the trial started, I was in Shapiro's office in Century City."; // Text
ie.interpreter.set("T", T);
PyObject answer = ie.interpreter.eval("RTE('None').WordPhraseRate(T)");
System.out.print(answer.toString());
}
}