Spark大数据分析实战【1.4】
6.5 Spark Streaming在线情感分析
本节将介绍如何使用Spark进行Twitter的情感分析。本例将通过Stanford NLP库中的情感分析组件——递归神经网络(Recursive Neural Network,RNN)对Twitter进行情感分析。
Stanford NLP Group是斯坦福大学自然语言处理的团队,开发了多个NLP工具,官方网址为:http://nlp.stanford.edu/software/index.shtml。其开发的工具包括以下内容。
1)Stanford CoreNLP:采用Java编写的面向英文的处理工具。主要功能包括分词、词性标注、命名实体识别、语法分析等。
2)Stanford Word Segmenter:采用CRF(条件随机场)算法进行分词,也是基于Java开发的,同时可以支持中文和Arabic。
3)Stanford POS Tagger:采用Java编写的面向英文、中文、法语、阿拉伯语、德语的命名实体识别工具。
4)Stanford Named Entity Recognizer:采用条件随机场模型的命名实体工具。
5)Stanford Parser:进行语法分析的工具,支持英文、中文、阿拉伯文和法语。
6)Stanford Classifier:采用Java编写的分类器。
将通过如下函数对文本进行情感分析,将文本中的内容进行解析,并通过Stanford NLP进行情感分析与打分。
import java.util.Properties import edu.stanford.nlp.ling.CoreAnnotations import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations import edu.stanford.nlp.pipeline.StanfordCoreNLP import edu.stanford.nlp.sentiment.SentimentCoreAnnotationsimport scala.collection.JavaConversions._ import scala.collection.mutable.ListBuffer object SentimentAnalysisUtils { val nlpProps = { val props = new Properties() props.setProperty("annotators", "tokenize, ssplit, pos, lemma, parse, sentiment") props }d ef detectSentiment(message: String): SENTIMENT_TYPE = { // 初始化 val pipeline = new StanfordCoreNLP(nlpProps) // 处理每一条输入的Twitter val annotation = pipeline.process(message) var