Created
December 12, 2019 20:35
-
-
Save ssaurel/f6c8bc809987a7e955c8fc948b4a89de to your computer and use it in GitHub Desktop.
Analyze sentiment for Bitcoin Sentiment Analyzer on the SSaurel's Blog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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