gpt4 book ai didi

java - 斯坦福 nlp 的情感分析不起作用

转载 作者:行者123 更新时间:2023-11-29 06:57:10 24 4
gpt4 key购买 nike

我正在尝试使用 stanford nlp 来获取文本的情绪:这是我的代码:

import java.util.Properties;

import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.rnn.RNNCoreAnnotations;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.util.CoreMap;

public class SentimentAnalyzer {

public static void main(String[] args) {
findSentiment("");
}

public static void findSentiment(String line) {
line = "I started taking the little pill about 6 years ago.";
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, parse, sentiment");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
int mainSentiment = 0;
if (line != null && line.length() > 0) {
int longest = 0;
Annotation annotation = pipeline.process(line);
for (CoreMap sentence : annotation
.get(CoreAnnotations.SentencesAnnotation.class)) {
Tree tree = sentence
.get(SentimentCoreAnnotations.AnnotatedTree.class);
int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
String partText = sentence.toString();
if (partText.length() > longest) {
mainSentiment = sentiment;
longest = partText.length();
}

}
}
if (mainSentiment == 2 || mainSentiment > 4 || mainSentiment < 0) {
System.out.println("Neutral " + line);
}
else{
}
/*
* TweetWithSentiment tweetWithSentiment = new TweetWithSentiment(line,
* toCss(mainSentiment)); return tweetWithSentiment;
*/

}
}

我还使用此链接中的说明: https://blog.openshift.com/day-20-stanford-corenlp-performing-sentiment-analysis-of-twitter-using-java/

但是我得到以下错误:

Exception in thread "main" java.lang.NullPointerException
at edu.stanford.nlp.rnn.RNNCoreAnnotations.getPredictedClass(RNNCoreAnnotations.java:58)
at SentimentAnalyzer.findSentiment(SentimentAnalyzer.java:27)
at SentimentAnalyzer.main(SentimentAnalyzer.java:14)

指向这一行的是:

    Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class);

最佳答案

改用这个:

Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class);

编辑:要获得正面、负面和中立的评论,请使用此代码段:

switch (mainSentiment) {
case 0:
return "Very Negative";
case 1:
return "Negative";
case 2:
return "Neutral";
case 3:
return "Positive";
case 4:
return "Very Positive";
default:
return "";
}

关于java - 斯坦福 nlp 的情感分析不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32336293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com