Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Created December 12, 2019 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ssaurel/f6c8bc809987a7e955c8fc948b4a89de to your computer and use it in GitHub Desktop.
Save ssaurel/f6c8bc809987a7e955c8fc948b4a89de to your computer and use it in GitHub Desktop.
Analyze sentiment for Bitcoin Sentiment Analyzer on the SSaurel's Blog
enum TypeSentiment {
VERY_NEGATIVE(0), NEGATIVE(1), NEUTRAL(2), POSITIVE(3), VERY_POSITIVE(4);
int index;
private TypeSentiment(int index) {
this.index = index;
}
public static TypeSentiment fromIndex(int index) {
for (TypeSentiment typeSentiment: values()) {
if (typeSentiment.index == index) {
return typeSentiment;
}
}
return TypeSentiment.NEUTRAL;
}
}
public static TypeSentiment analyzeSentiment(String text) {
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, parse, sentiment");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
int mainSentiment = 0;
if (text != null && text.length() > 0) {
int longest = 0;
Annotation annotation = pipeline.process(text);
for (CoreMap sentence: annotation.get(CoreAnnotations.SentencesAnnotation.class)) {
Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class);
int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
String partText = sentence.toString();
if (partText.length() > longest) {
mainSentiment = sentiment;
longest = partText.length();
}
}
}
return TypeSentiment.fromIndex(mainSentiment);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment