今天學習如何使用斯坦福CoreNLP Java API來進行 情感分析(sentiment analysis) 。前幾天,我還寫了一篇關于如何使用TextBlob API 在Python裡做情感分析 ,我已經開發了一個應用程式,會篩選出給定關鍵詞的推文(tweets)的情感,現在看看它能做什麼。
應用
該示範應用程式在OpenShift
http://sentiments-t20.rhcloud.com/運作,它有兩個功能:
- 第一個功能是,如果你給定Twitter搜尋條件的清單會,它會顯示最近20推關于給定的搜尋詞的情緒。必須要勾選下圖所示的複選框來啟用此功能,(情感)積極的推文将顯示綠色,而消極的推文是紅色的。
- 第二個功能是做一些文字上的情感分析,如下圖
什麼是斯坦福CoreNLP?
斯坦福CoreNLP是一個Java自然語言分析庫,它內建了所有的自然語言處理工具,包括詞性的終端(POS)标注器,命名實體識别(NER),分析器,對指代消解系統,以及情感分析工具,并提供英語分析的模型檔案。
準備
- 基本的Java知識是必需的,安裝最新的Java開發工具包(JDK ),可以是 OpenJDK 7 或 Oracle JDK 7 。
- 從官方網站下載下傳 斯坦福CoreNLP包
- 注冊一個 OpenShift帳戶 ,它是完全免費的,可以配置設定給每個使用者1.5 GB的記憶體和3 GB的磁盤空間。
- 安裝RHC用戶端工具,需要有ruby 1.8.7或更新的版本,如果已經有ruby gem,輸入
,確定它是最新版本。要更新RHC的話,執行指令sudo gem install rhc
,如需其他協助安裝RHC指令行工具,請參閱該頁面: https://www.openshift.com/developers/rhc-client-tools-installsudo gem update rhc
- 通過
指令設定您的OpenShift帳戶,此指令将幫助你建立一個命名空間,并上傳你的SSH keys到OpenShift伺服器。rhc setup
Github倉庫
今天的示範應用程式的代碼可以在GitHub找到:
day20-stanford-sentiment-analysis-demo在兩分鐘内啟動并運作SentimentsApp
開始建立應用程式,名稱為
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
這将為應用程式建立一個容器,設定所有需要的SELinux政策和cgroup的配置,OpenShift也将建立一個私人git倉庫并克隆到本地。然後,它會複制版本庫到本地系統。最後,OpenShift會給外界提供一個DNS,該應用程式将在
http://newsapp-{domain-name}.rhcloud.com/ 下可以通路(将 domain-name 更換為自己的域名)。
該應用程式還需要對應Twitter應用程式的4個環境變量,通過去
https://dev.twitter.com/apps/new建立一個新的Twitter應用程式,然後建立如下所示的4個環境變量。
$ 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
重新啟動應用程式,以確定伺服器可以讀取環境變量。
$ rhc restart-app --app sentimentsapp
開始在
pom.xml
中為
stanford-corenlp
和
twitter4j
增加Maven的依賴關系,使用3.3.0版本斯坦福corenlp作為情感分析的API。
<dependency>
<groupId>edu.stanford.nlp</groupId>
<artifactId>stanford-corenlp</artifactId>
<version>3.3.0</version>
</dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<version>[3.0,)</version>
該twitter4j依賴關系需要Twitter搜尋。
通過更新
pom.xml
檔案裡的幾個特性将Maven項目更新到Java 7:
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
現在就可以更新Maven項目了(右鍵單擊>Maven>更新項目)。
啟用CDI
使用CDI來進行依賴注入。CDI、上下文和依賴注入是一個Java EE 6規範,能夠使依賴注入在Java EE 6的項目中。
在
src/main/webapp/WEB-INF
檔案夾下建一個名為
beans.xml
中一個新的XML文件,啟動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的關鍵字
建立了一個新的類
TwitterSearch
,它使用Twitter4J API來搜尋Twitter關鍵字。該API需要的Twitter應用程式配置參數,使用的環境變量得到這個值,而不是寫死。
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) {
// ignore
e.printStackTrace();
}
return Collections.emptyList();
}
}
在上面的代碼中,篩選了Twitter的搜尋結果,以確定沒有轉推(retweet)、或帶連結的推文、或有圖檔的推文,這樣做的原因是為了確定我們得到的是有文字的推。
情感分析器(SentimentAnalyzer)
建立了一個叫
SentimentAnalyzer
的類,這個類就是對某一條推文進行情感分析的。
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;
複制
englishPCFG.ser.gz
sentiment.ser.gz
模型到
src/main/resources/edu/stanford/nlp/models/lexparser
src/main/resources/edu/stanford/nlp/models/sentiment
檔案夾下。
建立SentimentsResource
最後,建立了JAX-RS資源類。
public class SentimentsResource {
@Inject
private SentimentAnalyzer sentimentAnalyzer;
private 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;
上述代碼執行以下操作:
- 檢查搜尋關鍵字(searchkeywords)是否“不是無效且不為空”,然後将其拆分到一個數組裡,隻考慮三個搜尋條件。
- 然後對每一個搜尋條件找到對應的推文,并做情感分析。
- 最後将傳回結果清單給使用者。