2016-09-22 55 views
0

我主要使用Python和Java新增功能。不过,我正在尝试编写一个Java程序,并通过Py4j Python包使其在Python中工作。下面的程序是我从一个例子改编的。我遇到了一个编译错误。你可以点亮一下吗?我很确定这是基本错误。谢谢。通过Python中的py4j编译Java corenlp情感评分程序的错误

> compile error: incompatible type: SimpleMatrix cannot be converted to String: return senti_scores. 
> intended input in Python: 
app = CoreNLPSentiScore() 
app.findSentiment("I like this book") 
intended output: matrix: Type = dense , numRows = 5 , numCols = 1 
0.016 
0.037 
0.132 
0.618 
0.196 

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; 
     //System.out.println(senti_score); 
    } 

} 

回答

1

Java是面向对象的程序,但它不像python,一切都被认为是对象。

在你上面提到的程序中。有一种方法findsentiment正在返回SimpleMatrix,但在方法声明中它是String。

解决方案 - 你可以在你的类SimpleMatrix此改变一个toString()方法,并在返回senti_score返回senti_score.toString()

+0

谢谢!它现在应该编译。不过,我在Python中使用了nullpointerexception。会引发另一个问题。 –