我主要使用 Python 和 Java 新手。但是我正在尝试编写一个 Java 程序并通过 Py4j Python 包使其在 Python 中工作。以下程序是我从一个例子改编的。我遇到了编译错误。你能解释一下吗?我很确定这是基本错误。谢谢。
> 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);
}
}