最近选修的大数据挖掘课上需要做关于情感分析的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的相关库功能还是很强大的,大家可以用类似的方法做自己感兴趣的文本的情感分析。

python实现情感分析_利用python实现简单情感分析相关推荐

  1. python异常值处理实例_利用Python进行异常值分析实例代码

    前言 异常值是指样本中的个别值,也称为离群点,其数值明显偏离其余的观测值.常用检测方法3σ原则和箱型图.其中,3σ原则只适用服从正态分布的数据.在3σ原则下,异常值被定义为观察值和平均值的偏差超过3倍 ...

  2. python做股票分析_利用Python进行股票投资组合分析(调试)

    pythonsp500-robo-advisor-edition Python for Financial Analyses 需要的镜像文件和数据--Robo Advisor edition. 小结 ...

  3. python做一个星座分析_利用python输出星座的方法

    利用python输出星座的方法 发布时间:2020-09-23 12:12:36 来源:亿速云 阅读:84 作者:小新 这篇文章将为大家详细讲解有关利用python输出星座的方法,小编觉得挺实用的,因 ...

  4. python电商数据挖掘_利用Python爬取淘宝商品并数据挖掘与分析实战!此乃大型项目!...

    项目内容 本案例选择>> 商品类目:沙发: 数量:共100页 4400个商品: 筛选条件:天猫.销量从高到低.价格500元以上. 项目目的 1. 对商品标题进行文本分析 词云可视化 2. ...

  5. python删除异常值代码_利用Python进行异常值分析实例代码

    前言 异常值是指样本中的个别值,也称为离群点,其数值明显偏离其余的观测值.常用检测方法3σ原则和箱型图.其中,3σ原则只适用服从正态分布的数据.在3σ原则下,异常值被定义为观察值和平均值的偏差超过3倍 ...

  6. 利用python进行数据分析 笔记_利用python进行数据分析--(阅读笔记一)

    原博文 2016-06-17 23:21 − 以此记录阅读和学习<利用Python进行数据分析>这本书中的觉得重要的点! 第一章:准备工作 1.一组新闻文章可以被处理为一张词频表,这张词频 ...

  7. python制作电脑软件_利用PYTHON制作桌面版爬虫软件(一)

    抱歉,对长沙房地产数据的挖掘与分析[三],想了蛮久,觉得对自己的分析结果不是很理想.等我完善好了,我再发出来吧.今天继续开启新的一专题.主要讲解如何用PYTHON实现简单的桌面软件的制作. 题外话,我 ...

  8. python itchat 无法登录_利用python实现在微信群刷屏的方法

    hello,我是小小炽,这是我写的第一篇博客,写博客一直都想在写,但是苦于能力尚浅,在各位大牛面前那既然是关公面前耍大刀了,但是其实想来每一个大牛不也是从一个小白慢慢进步学习从而达到一定的高度的吗,而 ...

  9. python post请求 上传图片_利用python模拟实现POST请求提交图片的方法

    本文主要给大家介绍的是关于利用python模拟实现POST请求提交图片的方法,分享出来供大家参考学习,下面来一看看详细的介绍: 使用requests来模拟HTTP请求本来是一件非常轻松的事情,比如上传 ...

最新文章

  1. 用T-SQL得到数据库的可视化结构
  2. 【XAduio2】6.如何枚举音频设备
  3. VTK:Video之OggTheora
  4. redhat 安装Rabbitmq
  5. [Abp 源码分析]多语言(本地化)处理
  6. 图像分割——基于二维灰度直方图的阈值处理
  7. JavaScript窗体控制函数
  8. 敲低这个基因就可以开怀大吃了!诺奖技术助力编辑蛋白质组!NGS可使临床治疗受益!...
  9. Python 中文Key 报错问题
  10. 轴承配合公差表查询_如何选择轴承公差和配合,才能更好保证电机轴承系统的运行?...
  11. LinkedList线程安全问题
  12. HP刀片服务器C7000-Cisco网络模块配置指南
  13. Android ADB 你想要的都在这
  14. Hbase RegionServer 宕机
  15. 1. 软件开发流程与QA工作流程
  16. 6678-GPIO基础(1)
  17. springside4配置环境时无法下载到两个核心包
  18. 远程办公新常态,为什么需要“零信任”模式?
  19. Python金融领域人工智能教程
  20. 《云计算核心技术剖析》-云计算的架构

热门文章

  1. mysql怎么截取时分秒_mysql中的截取函数及其实例
  2. 值得收藏的十个销售类网站(整理),给想做销售的人用
  3. 干货 | API开放提升效率和安全性攻略
  4. 国防科技大学903计算机专业综合,2021年国防科技大学电子信息(085400)考研专业目录_硕士研究生考试范围 - 学途吧...
  5. 安装npm及cnpm(Windows)
  6. Webots 机器人仿真平台(十) 添加camera相机
  7. 基于小爱平台的语音技能开发
  8. 数字电视机顶盒的接收过程
  9. 操作系统3--进程的同步
  10. 单因素设计一元定量资料差异性分析(一)-- 单组设计一元定量资料 t检验 与 符号秩和检验、配对设计一元定量资料 t检验 与 符号秩和检验