Day 20: 斯坦福CoreNLP —— 用Java给Twitter进行情感分析
今天學(xué)習(xí)如何使用斯坦福CoreNLP Java API來(lái)進(jìn)行情感分析(sentiment analysis)。前幾天,我還寫(xiě)了一篇關(guān)于如何使用TextBlob API在Python里做情感分析,我已經(jīng)開(kāi)發(fā)了一個(gè)應(yīng)用程序,會(huì)篩選出給定關(guān)鍵詞的推文(tweets)的情感,現(xiàn)在看看它能做什么。
應(yīng)用
該演示應(yīng)用程序在OpenShift http://sentiments-t20.rhcloud.com/ 運(yùn)行,它有兩個(gè)功能:
第一個(gè)功能是,如果你給定Twitter搜索條件的列表會(huì),它會(huì)顯示最近20推關(guān)于給定的搜索詞的情緒。必須要勾選下圖所示的復(fù)選框來(lái)啟用此功能,(情感)積極的推文將顯示綠色,而消極的推文是紅色的。
第二個(gè)功能是做一些文字上的情感分析,如下圖
什么是斯坦福CoreNLP?
斯坦福CoreNLP是一個(gè)Java自然語(yǔ)言分析庫(kù),它集成了所有的自然語(yǔ)言處理工具,包括詞性的終端(POS)標(biāo)注器,命名實(shí)體識(shí)別(NER),分析器,對(duì)指代消解系統(tǒng),以及情感分析工具,并提供英語(yǔ)分析的模型文件。
準(zhǔn)備
Github倉(cāng)庫(kù)
今天的演示應(yīng)用程序的代碼可以在GitHub找到:day20-stanford-sentiment-analysis-demo
在兩分鐘內(nèi)啟動(dòng)并運(yùn)行SentimentsApp
開(kāi)始創(chuàng)建應(yīng)用程序,名稱(chēng)為sentimentsapp。
$ rhc create-app sentimentsapp jbosseap --from-code=https://github.com/shekhargulati/day20-stanford-sentiment-analysis-demo.git還可以使用如下指令:
$ rhc create-app sentimentsapp jbosseap -g medium --from-code=https://github.com/shekhargulati/day20-stanford-sentiment-analysis-demo.git這將為應(yīng)用程序創(chuàng)建一個(gè)容器,設(shè)置所有需要的SELinux政策和cgroup的配置,OpenShift也將創(chuàng)建一個(gè)私人git倉(cāng)庫(kù)并克隆到本地。然后,它會(huì)復(fù)制版本庫(kù)到本地系統(tǒng)。最后,OpenShift會(huì)給外界提供一個(gè)DNS,該應(yīng)用程序?qū)⒃趆ttp://newsapp-{domain-name}.rhcloud.com/ 下可以訪問(wèn)(將 domain-name 更換為自己的域名)。
該應(yīng)用程序還需要對(duì)應(yīng)Twitter應(yīng)用程序的4個(gè)環(huán)境變量,通過(guò)去https://dev.twitter.com/apps/new 創(chuàng)建一個(gè)新的Twitter應(yīng)用程序,然后創(chuàng)建如下所示的4個(gè)環(huán)境變量。
$ rhc env set TWITTER_OAUTH_ACCESS_TOKEN=<please enter value> -a sentimentsapp$ rhc env set TWITTER_OAUTH_ACCESS_TOKEN_SECRET=<please enter value> -a sentimentsapp$rhc env set TWITTER_OAUTH_CONSUMER_KEY=<please enter value> -a sentimentsapp$rhc env set TWITTER_OAUTH_CONSUMER_SECRET=<please enter value> -a sentimentsapp重新啟動(dòng)應(yīng)用程序,以確保服務(wù)器可以讀取環(huán)境變量。
$ rhc restart-app --app sentimentsapp開(kāi)始在pom.xml中為stanford-corenlp和twitter4j增加Maven的依賴(lài)關(guān)系,使用3.3.0版本斯坦福corenlp作為情感分析的API。
<dependency><groupId>edu.stanford.nlp</groupId><artifactId>stanford-corenlp</artifactId><version>3.3.0</version> </dependency><dependency><groupId>org.twitter4j</groupId><artifactId>twitter4j-core</artifactId><version>[3.0,)</version> </dependency>該twitter4j依賴(lài)關(guān)系需要Twitter搜索。
通過(guò)更新 pom.xml 文件里的幾個(gè)特性將Maven項(xiàng)目更新到Java 7:
<maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target>現(xiàn)在就可以更新Maven項(xiàng)目了(右鍵單擊>Maven>更新項(xiàng)目)。
啟用CDI
使用CDI來(lái)進(jìn)行依賴(lài)注入。CDI、上下文和依賴(lài)注入是一個(gè)Java EE 6規(guī)范,能夠使依賴(lài)注入在Java EE 6的項(xiàng)目中。
在 src/main/webapp/WEB-INF 文件夾下建一個(gè)名為beans.xml中一個(gè)新的XML文件,啟動(dòng)CDI
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"></beans>搜索Twitter的關(guān)鍵字
創(chuàng)建了一個(gè)新的類(lèi)TwitterSearch,它使用Twitter4J API來(lái)搜索Twitter關(guān)鍵字。該API需要的Twitter應(yīng)用程序配置參數(shù),使用的環(huán)境變量得到這個(gè)值,而不是硬編碼。
import java.util.Collections; import java.util.List;import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.conf.ConfigurationBuilder;public class TwitterSearch {public List<Status> search(String keyword) {ConfigurationBuilder cb = new ConfigurationBuilder();cb.setDebugEnabled(true).setOAuthConsumerKey(System.getenv("TWITTER_OAUTH_CONSUMER_KEY")).setOAuthConsumerSecret(System.getenv("TWITTER_OAUTH_CONSUMER_SECRET")).setOAuthAccessToken(System.getenv("TWITTER_OAUTH_ACCESS_TOKEN")).setOAuthAccessTokenSecret(System.getenv("TWITTER_OAUTH_ACCESS_TOKEN_SECRET"));TwitterFactory tf = new TwitterFactory(cb.build());Twitter twitter = tf.getInstance();Query query = new Query(keyword + " -filter:retweets -filter:links -filter:replies -filter:images");query.setCount(20);query.setLocale("en");query.setLang("en");;try {QueryResult queryResult = twitter.search(query);return queryResult.getTweets();} catch (TwitterException e) {// ignoree.printStackTrace();}return Collections.emptyList();}}在上面的代碼中,篩選了Twitter的搜索結(jié)果,以確保沒(méi)有轉(zhuǎn)推(retweet)、或帶鏈接的推文、或有圖片的推文,這樣做的原因是為了確保我們得到的是有文字的推。
情感分析器(SentimentAnalyzer)
創(chuàng)建了一個(gè)叫SentimentAnalyzer的類(lèi),這個(gè)類(lèi)就是對(duì)某一條推文進(jìn)行情感分析的。
public class SentimentAnalyzer {public TweetWithSentiment findSentiment(String line) {Properties props = new Properties();props.setProperty("annotators", "tokenize, ssplit, parse, sentiment");StanfordCoreNLP pipeline = new StanfordCoreNLP(props);int mainSentiment = 0;if (line != null && line.length() > 0) {int longest = 0;Annotation annotation = pipeline.process(line);for (CoreMap sentence : annotation.get(CoreAnnotations.SentencesAnnotation.class)) {Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class);int sentiment = RNNCoreAnnotations.getPredictedClass(tree);String partText = sentence.toString();if (partText.length() > longest) {mainSentiment = sentiment;longest = partText.length();}}}if (mainSentiment == 2 || mainSentiment > 4 || mainSentiment < 0) {return null;}TweetWithSentiment tweetWithSentiment = new TweetWithSentiment(line, toCss(mainSentiment));return tweetWithSentiment;} }復(fù)制 englishPCFG.ser.gz 和 sentiment.ser.gz 模型到src/main/resources/edu/stanford/nlp/models/lexparser 和src/main/resources/edu/stanford/nlp/models/sentiment 文件夾下。
創(chuàng)建SentimentsResource
最后,創(chuàng)建了JAX-RS資源類(lèi)。
public class SentimentsResource {@Injectprivate SentimentAnalyzer sentimentAnalyzer;@Injectprivate TwitterSearch twitterSearch;@GET@Produces(value = MediaType.APPLICATION_JSON)public List<Result> sentiments(@QueryParam("searchKeywords") String searchKeywords) {List<Result> results = new ArrayList<>();if (searchKeywords == null || searchKeywords.length() == 0) {return results;}Set<String> keywords = new HashSet<>();for (String keyword : searchKeywords.split(",")) {keywords.add(keyword.trim().toLowerCase());}if (keywords.size() > 3) {keywords = new HashSet<>(new ArrayList<>(keywords).subList(0, 3));}for (String keyword : keywords) {List<Status> statuses = twitterSearch.search(keyword);System.out.println("Found statuses ... " + statuses.size());List<TweetWithSentiment> sentiments = new ArrayList<>();for (Status status : statuses) {TweetWithSentiment tweetWithSentiment = sentimentAnalyzer.findSentiment(status.getText());if (tweetWithSentiment != null) {sentiments.add(tweetWithSentiment);}}Result result = new Result(keyword, sentiments);results.add(result);}return results;} }上述代碼執(zhí)行以下操作:
今天就是這些,歡迎反饋。
原文 Day 20: Stanford CoreNLP--Performing Sentiment Analysis of Twitter using Java
翻譯整理 SegmentFault
總結(jié)
以上是生活随笔為你收集整理的Day 20: 斯坦福CoreNLP —— 用Java给Twitter进行情感分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Day 19: EmberJS 入门指南
- 下一篇: Day 21:Docker 入门教程