利用python实现简单情感分析

最近选修的大数据挖掘课上需要做关于情感分析的pre,自己也做了一些准备工作,就像把准备的内容稍微整理一下写出来,下次再做类似项目的时候也有个参考。

情感分析是什么?

文本情感分析是指用自然语言处理(NLP)、文本挖掘以及计算机语言学等方法对带有情感色彩的主观性文本进行分析、处理、归纳和推理的过程。 情感分析是文本分类的一个分支,通过对带有情感色彩(褒义贬义/正向负向)的主观性文本进行分析,以确定该文本的情感倾向。
情感分析应用的领域非常广泛:比如说商品的评论挖掘、电影推荐、股市预测等等

情感分析的方法

目前主流的情感分析方法主要有两种:基于情感词典的情感分析和基于机器学习的情感分析
1、 基于情感词典的情感分析
是指根据已构建的情感词典,对待分析文本进行文本处理抽取情感词,计算该文本的情感倾向。最终分类效果取决于情感词典的完善性。这也是一种比较简单的方法。目前已经有一些比较不错的情感词典:比如说知网情感分析用词语集,台湾大学情感词典,清华大学褒贬词词典,BosonNLP情感词典等等
逻辑:


image.png

2、基于机器学习的情感分析
情感分析本质上也是个二分类的问题,可以采用机器学习的方法识别,选取文本中的情感词作为特征词,将文本矩阵化,利用逻辑回归( logistic Regression ), 朴素贝叶斯(Naive Bayes),支持向量机(SVM)等方法进行分类。最终分类效果取决于训练文本的选择以及正确的情感标注。
逻辑:


image.png

现在尝试一下用python实现情感分析:

需要用到的工具:
NLTK库(natural language toolkit):是一套基于python的自然语言处理工具集。
Sklearn库( Scikit-learn ):机器学习中最简单高效的数据挖掘和数据分析工具
Textblob库:适用于python的开源的文本处理库,它可以用来执行很多自然语言处理的任务

完整代码如下:
1、使用Nltk进行简单情感分析

# 导入库
import nltk
#构建两个由元组构建的列表
pos_tweets = [('I love this car', 'positive'),
    ('This view is amazing', 'positive'),
    ('I feel great this morning', 'positive'),
    ('I am so excited about the concert', 'positive'),
    ('He is my best friend', 'positive')]

neg_tweets = [('I do not like this car', 'negative'),
    ('This view is horrible', 'negative'),
    ('I feel tired this morning', 'negative'),
    ('I am not looking forward to the concert', 'negative'),
    ('He is my enemy', 'negative')]
## 分词:保留长度大于3的词进行切割
tweets = []
for (words, sentiment) in pos_tweets + neg_tweets:
    words_filtered = [e.lower() for e in words.split() if len(e) >= 3]  
    tweets.append((words_filtered, sentiment))
## 用于测试的tweets
test_tweets = [
    (['feel', 'happy', 'this', 'morning'], 'positive'),
    (['larry', 'friend'], 'positive'),
    (['not', 'like', 'that', 'man'], 'negative'),
    (['house', 'not', 'great'], 'negative'),
    (['your', 'song', 'annoying'], 'negative')]

提取特征

#get the word lists of tweets
def get_words_in_tweets(tweets):
    all_words = []
    for (words, sentiment) in tweets:
        all_words.extend(words)
    return all_words
# get the unique word from the word list
def get_word_features(wordlist):
    wordlist = nltk.FreqDist(wordlist)  # 统计词语出现的频次
    word_features = wordlist.keys()
    return word_features
word_features = get_word_features(get_words_in_tweets(tweets))  ## 目的是获得一个分词的列表
' '.join(word_features)  
## 特征提取
def extract_features(document):
    document_words = set(document)  # set() 函数创建一个无序不重复元素集
    features = {}
    for word in word_features:
        features['contains(%s)' % word] = (word in document_words)   
    return features # 是否包含测试集中的单词

构建分类器

training_set = nltk.classify.util.apply_features(extract_features,tweets) ##  构建一个分类训练集
classifier = nltk.NaiveBayesClassifier.train(training_set)  ##  构建一个朴素贝叶斯分类器
def train(labeled_featuresets, estimator=nltk.probability.ELEProbDist):
    # Create the P(label) distribution
    label_probdist = estimator(label_freqdist)
    # Create the P(fval|label, fname) distribution
    feature_probdist = {}
    model = NaiveBayesClassifier(label_probdist, feature_probdist)
    return model

验证:

##测试1正确
tweet_positive = 'Harry is my friend'
classifier.classify(extract_features(tweet_positive.split()))
## 测试2正确
tweet_negative = 'Larry is not my friend'
classifier.classify(extract_features(tweet_negative.split()))
## 测试3错误
tweet_negative2 = 'Your song is annoying'
classifier.classify(extract_features(tweet_negative2.split()))
##验证效果
def classify_tweet(tweet):
    return classifier.classify(extract_features(tweet)) 
total = accuracy = float(len(test_tweets))
for tweet in test_tweets:
    if classify_tweet(tweet[0]) != tweet[1]:
        accuracy -= 1
print('Total accuracy: %f%% (%d/5).' % (accuracy / total * 100, accuracy))

最后输出的accuracy score 为:Total accuracy: 80.000000% (4/5).

2、尝试一下sklearn的分类器

# nltk有哪些分类器
nltk_classifiers = dir(nltk)
for i in nltk_classifiers:
    if 'Classifier' in i:
        print(i)
#使用sklearn分类器
from sklearn.svm import LinearSVC
from nltk.classify.scikitlearn import SklearnClassifier
classif = SklearnClassifier(LinearSVC())
svm_classifier = classif.train(training_set)
##  测试
tweet_negative2 = 'Your song is annoying'
svm_classifier.classify(extract_features(tweet_negative2.split()))

3 、使用TextBlob进行情感分析
TextBlob是一个用python编写的开源的文本处理库,它可以用来执行很多自然语言处理的任务,比如,词性标注、名词性成分提取、情感分析、文本翻译等等

##导入相关库,下载资源
import nltk
nltk.download('averaged_perceptron_tagger')
nltk.download('punkt')
nltk.download('brown')
nltk.download('wordnet')
from textblob import TextBlob
text = '''
The titular threat of The Blob has always struck me as the ultimate movie
monster: an insatiably hungry, amoeba-like mass able to penetrate
virtually any safeguard, capable of--as a doomed doctor chillingly
describes it--"assimilating flesh on contact.
Snide comparisons to gelatin be damned, it's a concept with the most
devastating of potential consequences, not unlike the grey goo scenario
proposed by technological theorists fearful of
artificial intelligence run rampant.
'''
blob = TextBlob(text)
##  词性标注
print('词性标注')
print(blob.tags)
##  分词
print('将句子切分成词或者句子')
token = blob.words
for w in token:
    print(w)
 计算句子情感值
for sentence in blob.sentences:
    print(sentence + '------>'+ str(sentence.sentiment.polarity))

输出结果:


image.png

python的相关库功能还是很强大的,大家可以用类似的方法做自己感兴趣的文本的情感分析。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,812评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,626评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,144评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,052评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,925评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,035评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,461评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,150评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,413评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,501评论 2 307
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,277评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,159评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,528评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,868评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,143评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,407评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,615评论 2 335