user7575479
user7575479

Reputation: 15

Java - The method is undefined for the type

I am carrying out sentiment analysis on movie reviews using Stanford CoreNLP. Since it only works on sentences instead of whole documents I am writing my own code to establish an average sentiment for the entire review. I am taking each sentence of the review, establishing its sentiment and placing it in an array. I am using a scoring system for the sentiments so that I can average a score and therefore an average sentiment. However when trying to populate the sentiment array i receive the following error:

The method get is undefined for the type String

My code is as follows:

import java.io.*;
import java.util.*;

import edu.stanford.nlp.coref.CorefCoreAnnotations;

import edu.stanford.nlp.coref.data.CorefChain;
import edu.stanford.nlp.io.*;
import edu.stanford.nlp.io.EncodingPrintWriter.out;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.pipeline.CoreNLPProtos.Sentiment;
import edu.stanford.nlp.semgraph.SemanticGraph;
import edu.stanford.nlp.semgraph.SemanticGraphCoreAnnotations;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.trees.*;
import edu.stanford.nlp.util.*;
import edu.stanford.nlp.sentiment.Evaluate;
import org.apache.commons.io.FileUtils;

/** This class demonstrates building and using a Stanford CoreNLP pipeline. */
public class sentimentMain {

  /** Usage: java -cp "*" StanfordCoreNlpDemo [inputFile [outputTextFile [outputXmlFile]]] */
  public static void main(String[] args) throws IOException {

      //ArrayList<String> Sentences = new ArrayList<String>();
      //ArrayList<String> sentence_sentiment = new ArrayList<String>();

    // set up optional output files
    PrintWriter out;
    if (args.length > 1) {
      out = new PrintWriter(args[1]);
    } else {
      out = new PrintWriter(System.out);
    }
    PrintWriter xmlOut = null;
    if (args.length > 2) {
      xmlOut = new PrintWriter(args[2]);
    }
    // Add in sentiment
    Properties props = new Properties();
    props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref, sentiment");

    StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
    File[] files = new File("C:/stanford-corenlp-full-2016-10-31/dataset").listFiles();

    String line = null;

    try{
        for (File file : files) {
            if (file.exists()) {
                BufferedReader in = new BufferedReader(new FileReader(file));
                while((line = in.readLine()) != null)
                {
                    Annotation document = new Annotation(line);

                    // run all the selected Annotators on this text
                    pipeline.annotate(document);
                    String str = FileUtils.readFileToString(file);

                    // this prints out the results of sentence analysis to file(s) in good formats
                    pipeline.prettyPrint(document, out);
                    if (xmlOut != null) {
                      pipeline.xmlPrint(document, xmlOut);
                    }

                    List<CoreMap> sentences = document.get(CoreAnnotations.SentencesAnnotation.class);
                    if (sentences != null && ! sentences.isEmpty()) {
                      CoreMap sentence = sentences.get(0);
                      for (CoreMap token : sentence.get(CoreAnnotations.TokensAnnotation.class)) {
                      }
                      Tree tree = sentence.get(TreeCoreAnnotations.TreeAnnotation.class);
                      tree.pennPrint(out);
                      SemanticGraph graph = sentence.get(SemanticGraphCoreAnnotations.CollapsedCCProcessedDependenciesAnnotation.class);   
                      Map<Integer, CorefChain> corefChains =
                          document.get(CorefCoreAnnotations.CorefChainAnnotation.class);
                      if (corefChains == null) { return; }
                      for (Map.Entry<Integer,CorefChain> entry: corefChains.entrySet()) {
                        for (CorefChain.CorefMention m : entry.getValue().getMentionsInTextualOrder()) {
                          // We need to subtract one since the indices count from 1 but the Lists start from 0
                          List<CoreLabel> tokens = sentences.get(m.sentNum - 1).get(CoreAnnotations.TokensAnnotation.class);
                        }
                      }
                      out.println("The first sentence overall sentiment rating is " + sentence.get(SentimentCoreAnnotations.SentimentClass.class));
                      Sentences.add(line);
                      sentence_sentiment.add(sentence.get(SentimentCoreAnnotations.SentimentClass.class));

                      //Sentences.forEach(s -> System.out.println(s));
                      //sentence_sentiment.forEach(s -> System.out.println(s));

                      averageSent(str);   
                    }
                }

                in.close();
            } else {
                System.out.println("File: " + file.getName() + file.toString());
            }
        }
    }catch(NullPointerException e){
        e.printStackTrace();
    }
    IOUtils.closeIgnoringExceptions(out);
    IOUtils.closeIgnoringExceptions(xmlOut);
  }

  public static void averageSent(String review) 
  { 
        //populate sentence array with each sentence of the review
        String [] sentences = review.split("[!?.:]+");

        //number of sentences in each review
        int review_sentences = review.split("[!?.:]+").length;

        //array of sentiments for each review
        String sentiments[] = new String[review_sentences];

        int total = 0;

        //populate sentiments array
        for (int i=0; i<= review_sentences; i++)
            {
                sentiments[i].add(sentences[i].get(SentimentCoreAnnotations.SentimentClass.class));
            }

        for (String sent: sentiments)
        {
            if (sent == "Very positive")
            {
                int veryPos = 4;
                total += veryPos;
            }
            else if (sent == "Positive")
            {
                int pos = 3;
                total += pos;
            }
            else if (sent == "Negative")
            {
                int neg = 2;
                total += neg;
            }
            else if (sent == "Very negative")
            {
                int veryNeg = 1;
                total += veryNeg;
            }
            else if (sent == "Neutral")
            {
                int neu = 0;
                total += neu;
            }

            //System.out.println("Total " +total);

            //int average = total/review_sent;
            //System.out.println("Average" + average);
    }

  }
}

If anyone can see what I'm doing wrong I would really appreciate it :)

Upvotes: 0

Views: 2325

Answers (2)

Mauro Piccotti
Mauro Piccotti

Reputation: 1847

Probably you have to review a bit your code, you are trying to call a .get method on a String variable:

String [] sentences = review.split("[!?.:]+");
...
sentences[i].get

Upvotes: 1

BackSlash
BackSlash

Reputation: 22243

This wont' work:

sentences[i].get(SentimentCoreAnnotations.SentimentClass.class)

Right before it:

String [] sentences = review.split("[!?.:]+");

That line produces an array of String objects, and the String class doesn't have a get method.

Upvotes: 1

Related Questions