0.Download Stanford NLP Core Lib and import external lib stanford-corenlp-3.5.2-models.jar, stanford-corenlp-3.5.2.jar, stanford-corenlp-3.5.2-sources.jar and ejml-0.23.jar into this package.
1.Build this class NLP in Eclipse
import java.util.Properties;
import org.ejml.simple.SimpleMatrix;
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;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations.SentimentAnnotatedTree;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.util.CoreMap;
public class NLP {
static StanfordCoreNLP pipeline;
public static void init() {
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, parse, sentiment");
pipeline = new StanfordCoreNLP(props);
}
public static int findSentiment(String tweet) {
int mainSentiment = 0;
if (tweet != null && tweet.length() > 0) {
int longest = 0;
Annotation annotation = pipeline.process(tweet);
for (CoreMap sentence : annotation
.get(CoreAnnotations.SentencesAnnotation.class)) {
Tree tree = sentence
.get(SentimentAnnotatedTree.class);
int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
SimpleMatrix sentiment_new = RNNCoreAnnotations.getPredictions(tree);
String partText = sentence.toString();
if (partText.length() > longest) {
mainSentiment = sentiment;
longest = partText.length();
}
}
}
return mainSentiment;
}
}
2.Build a new class to parse your sentence with NLP
import java.util.ArrayList;
public class What2Think {
public static void main(String[] args) {
ArrayList<String> tweets = new ArrayList<String>();
tweets.add("In this country, \"democracy\" means pro-government. #irony");
NLP.init();
for(String tweet : tweets) {
System.out.println(tweet + " : " + NLP.findSentiment(tweet));
}
}
}
Run it