Skip to content

Instantly share code, notes, and snippets.

@shayanjm
Created July 17, 2014 15:59
Show Gist options
  • Save shayanjm/9ff17cf7b3f72b102407 to your computer and use it in GitHub Desktop.
Save shayanjm/9ff17cf7b3f72b102407 to your computer and use it in GitHub Desktop.
Sentiment analysis using Stanford CoreNLP in Clojure
(def nlp
(let [props (new java.util.Properties)]
(.setProperty props "annotators" "tokenize,ssplit,parse,sentiment")
(new edu.stanford.nlp.pipeline.StanfordCoreNLP props)))
(defn find-sentiment
"Determines the sentiment of each sentence in a given glob of text. Results in a collection of integers ranging from [0-4]: where 0 is 'Very negative', 2 is 'neutral', and 4 is 'Very positive'"
[blob]
(let [glob (apply str blob)]
(let [main-sentiment 0
longest 0]
(if (and (not (nil? glob)) (> (count glob) 0))
(let [annotation (.process nlp glob)]
(for [sentence (.get annotation edu.stanford.nlp.ling.CoreAnnotations$SentencesAnnotation)]
(let [tree (.get sentence edu.stanford.nlp.sentiment.SentimentCoreAnnotations$AnnotatedTree)
sentiment (edu.stanford.nlp.neural.rnn.RNNCoreAnnotations/getPredictedClass tree)
part-text (.toString sentence)]
(if (> (.length part-text) longest)
(int sentiment)))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment