CoreNLP 3.5.2中的空指针异常

时间:2018-03-18 17:24:08

标签: java stanford-nlp sentiment-analysis

所以,我有以下用Java编写的代码,它使用Stanford CoreNLP库来执行推文的情绪分析。

import java.util.*;
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;
public class NLPAnalysis 
{
static StanfordCoreNLP pipeline;

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

public static String findSentiment() {
    Scanner sc = new Scanner (System.in);
    String tweet = sc.next();
    String SentiReturn = "";
    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;

    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);  
            sentiment = RNNCoreAnnotations.getPredictedClass(tree);             
            SentiReturn = SentiClass[sentiment];
        }
    }
    return SentiReturn;
}

public static void main(String[] args) throws Exception
    {
    System.out.println("Enter your tweet:");
    String answer = findSentiment();
    System.out.println("The Sentiment:"+answer);
    }
}

我已根据先前对类似问题的回答将annotators设置为tokenize, parse, sentiment, pos,但我仍然在第33行获得NullPointerExceptionAnnotation annotation = pipeline.process(tweet);

请帮我解决这个问题。感谢。

0 个答案:

没有答案