2012-12-05 8 views
0

우선 Java 코딩을 위해 MacBook에서 Eclipse를 사용하고 있습니다. NLTK를 "자연 언어 처리에 사용하는"파이썬 코드를 작성 했으므로 멋지게 작동했습니다. 나는 자바에서 간단한 파이썬 코드를 호출하려고했는데 예상대로 또한 작동했다.Java에서 Python 메소드를 호출 할 때 import NLTK가 실패합니다.

하지만 난 NLTK를 사용하는 파이썬 코드를 호출하려고 할 때, import 문은 실패하지 않습니다 : "ImportError를을 : 없음 모듈 이름 NLTK"

파이썬은 NLTK를 찾을 수 있었다 것을 라이브러리에서 찾을 수 있지만 Java에서는 불가능합니다.

파이썬 코드와 자바 코드 모두에서 가져 오기 문을 사용하려고했지만 행운이 없었습니다. 여기

파이썬 코드 :

#!/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) 
. 
. 
. 

그리고 다음은 자바 코드 :

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

    } 
} 
+0

참조 http://stackoverflow.com/questions/1164810/using-python- from-within-java (NLTK 검색) – jdigital

답변

2

나는 차이가 성능이 무엇인지 잘 모르겠지만, 당신은 할 수 브리징이나 다른 문제에 대해 걱정하지 않으려는 경우 Java로 직접 스크립트를 호출하십시오. 다음과 같은 것.

파이썬, 파일에 이름 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 

자바 :

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(); 
     } 
    } 
} 
+0

이 방법을 시도했지만 특정 파이썬 메서드를 호출하고 Java에서 그 값을 반환 할 수 없었습니다. – user1483799

+0

파이썬에서 캡처 된 값을'print'해야하고, stdout에서 정보를 읽어야합니다. 또는 데이터를 파일에 쓰고 Java에서 해당 파일을 다시 열 수 있습니다. –

+0

그러나 실행할 수없는 코드의 예를 들려 줄 수 있습니까? –

관련 문제