2015-09-01 56 views
1

我想使用斯坦福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); 

有沒有人有任何想法?

回答

6

用這個代替:

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 ""; 
     } 
+0

非常感謝,現在的工作怎麼可以看看這個句子是否中立或正面或負面? –

+0

用代碼片段更新了評論,以顯示句子是神經,正面還是負面。 –

+0

U是真棒夥計:) –