简体   繁体   English

从Java调用Python方法时,import NLTK失败

[英]import NLTK fails when calling Python method from Java

First of all, I'm using Eclipse on MacBook for Java coding. 首先,我在MacBook上使用Eclipse进行Java编码。 I wrote a Python code that uses NLTK "for natural language processing" and it worked nicely. 我编写了一个使用NLTK“进行自然语言处理”的Python代码,它工作得很好。 I tried to call a simple Python code from Java and it also worked as expected. 我试图从Java调用一个简单的Python代码,它也按预期工作。

BUT when I tried to call the Python code that uses the NLTK, the import statement fails: "ImportError: No module named nltk" 但是当我尝试调用使用NLTK的Python代码时,import语句失败: “ImportError:没有名为nltk的模块”

It seems that Python was able to locate the NLTK library, but from Java it couldn't. 似乎Python能够找到NLTK库,但是从Java中却找不到。

I tried to have the import statement in both the Python code and the Java code but with no luck. 我试图在Python代码和Java代码中都有import语句,但没有运气。

Here is the Python code: 这是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)
.
.
.

And Here is the Java Code: 这是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());    

    }
}

I'm not sure what the differences are in performance, but you can just call the script directly in Java if you don't want to worry about bridging or other problems. 我不确定性能上的差异是什么,但如果你不想担心桥接或其他问题,你可以直接用Java调用脚本。 Something like the following. 像下面这样的东西。

Python , in a file named testing.py: Python ,在名为testing.py的文件中:

#!/usr/local/bin/python
# coding: UTF-8
import os, sys
from nltk.tokenize import word_tokenize # Tokenizer

if __name__ == "__main__":
    # If you want to read from a file instead of passing data
    #text = open(sys.argv[1]).read()

    # read the first argument passed to script
    text = sys.argv[1]

    tokens = word_tokenize(text)
    print tokens

Java : Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.File;

public class pythonfromjava{
    public static void main(String argv[]) {
        try{
            // for tilda expansion
            //if (filepath.startsWith("~" + File.separator)) {
                //filepath = System.getProperty("user.home") + filepath.substring(1);
            //}

            //ProcessBuilder builder = new ProcessBuilder("python", "-c", "import sys; import nltk; print \"whatever\"");
            ProcessBuilder builder = new ProcessBuilder("python", "testing.py", "four scores and seven years ago");
            builder.redirectErrorStream(true);
            Process p = builder.start();
            InputStream stdout = p.getInputStream();
            BufferedReader reader = new BufferedReader (new InputStreamReader(stdout));

            String line;
            while ((line = reader.readLine ()) != null) {
                System.out.println ("Stdout: " + line);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

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

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