2016-09-22 2 views
0

Я сделал программу анализа настроений Java, которая будет использоваться в Python через Py4j. Я могу создать объект Java в Python, но попытаюсь получить доступ к этому методу, он дает java.lang.NullPointerException. Не могли бы вы помочь? Благодарю.corenlp настроение Java-программа через Py4j в Python, вызывает ошибки

Код Java: он компилируется правильно, работает без ошибок.

import java.util.List; 
import java.util.Properties; 
import edu.stanford.nlp.ling.CoreAnnotations; 
import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations; 
import edu.stanford.nlp.pipeline.Annotation; 
import edu.stanford.nlp.pipeline.StanfordCoreNLP; 
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations.SentimentAnnotatedTree; 
import edu.stanford.nlp.trees.Tree; 
import edu.stanford.nlp.util.ArrayCoreMap; 
import edu.stanford.nlp.util.CoreMap; 
import py4j.GatewayServer; 
import org.ejml.simple.SimpleMatrix; 


public class CoreNLPSentiScore { 
static StanfordCoreNLP pipeline; 

    public static void init() { 
     Properties props = new Properties(); 
     props.setProperty("annotators", "tokenize, ssplit, parse, sentiment"); 
     pipeline = new StanfordCoreNLP(props); 

    } 

    public static void main(String[] args) { 
     CoreNLPSentiScore app = new CoreNLPSentiScore(); 
     // app is now the gateway.entry_point 
     GatewayServer server = new GatewayServer(app); 
     server.start(); 
    } 

    //public static void main(String tweet) { 
    //public static String findSentiment(String tweet) { 
    public String findSentiment(String tweet) { 
     //String SentiReturn = "2"; 
     //String[] SentiClass ={"very negative", "negative", "neutral", "positive", "very positive"}; 

     //Sentiment is an integer, ranging from 0 to 4. 
     //0 is very negative, 1 negative, 2 neutral, 3 positive and 4 very positive. 
     //int sentiment = 2; 
     SimpleMatrix senti_score = new SimpleMatrix(); 
     if (tweet != null && tweet.length() > 0) { 
      Annotation annotation = pipeline.process(tweet); 

      List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class); 
      if (sentences != null && sentences.size() > 0) { 

       ArrayCoreMap sentence = (ArrayCoreMap) sentences.get(0);     
       //Tree tree = sentence.get(SentimentAnnotatedTree.class); 
       Tree tree = sentence.get(SentimentAnnotatedTree.class); 
       senti_score = RNNCoreAnnotations.getPredictions(tree);    

       //SentiReturn = SentiClass[sentiment]; 
      } 
     } 
     //System.out.println(senti_score); 
     return senti_score.toString(); 
     //System.out.println(senti_score); 
    } 

} 

код Python:

from py4j.java_gateway import JavaGateway 
gateway = JavaGateway() 
app = gateway.entry_point 
test = 'i like this product' 
app.findSentiment(test) 

NullPointerException

Traceback (most recent call last): 

    File "<ipython-input-1-cefdf18ada67>", line 5, in <module> 
    app.findSentiment(test) 

    File "C:\Anaconda3\envs\sandbox\lib\site-packages\py4j\java_gateway.py", line 1026, in __call__ 
    answer, self.gateway_client, self.target_id, self.name) 

    File "C:\Anaconda3\envs\sandbox\lib\site-packages\py4j\protocol.py", line 316, in get_return_value 
    format(target_id, ".", name), value) 

Py4JJavaError: An error occurred while calling t.findSentiment.: java.lang.NullPointerException 
at CoreNLPSentiScore.findSentiment(CoreNLPSentiScore.java:43) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
at java.lang.reflect.Method.invoke(Unknown Source) 
at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237) 
at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) 
at py4j.Gateway.invoke(Gateway.java:280) 
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) 
at py4j.commands.CallCommand.execute(CallCommand.java:79) 
at py4j.GatewayConnection.run(GatewayConnection.java:214) 
at java.lang.Thread.run(Unknown Source) 
+0

Возможный дубликат [Что такое исключение NullPointerException и как его исправить?] (Http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix -it) – sidgate

+0

@sidgate Спасибо. Я прочитал хотя пост. Инициирование объекта не требует ввода. В методе findSentiment требуется вход String, для которого я добавил код Python. все еще есть эта проблема. –

ответ

1

Я считаю, что вы забыли назвать Init().

Это, кажется, строка # 43 (смотрите трассировки стека):

Annotation annotation = pipeline.process(tweet); 

трубопровода, вероятно, будет нулевым, поскольку она конкретизируется в Init() и инициализации() не вызывается в основном () или Python.

+0

Спасибо. хотя я даю некоторые другие ошибки. Но это решит проблему, которую я задаю ;-). Btw .. Я новичок в Java. Я в основном использую Python, по сравнению с Java, это действительно заставляет меня лениться думать о многом ... –

Смежные вопросы