-
NLP之情感分析:基于python编程(jieba库)实现中文文本情感分析(得到的是情感评分)
2018-12-06 20:47:01NLP之情感分析:基于python编程(jieba库)实现中文文本情感分析(得到的是情感评分) 输出结果 1、测试对象 data1= '今天上海的天气真好!我的心情非常高兴!如果去旅游的话我会非常兴奋!和你一起去旅游我会更加...NLP之情感分析:基于python编程(jieba库)实现中文文本情感分析(得到的是情感评分)
目录
输出结果
1、测试对象
data1= '今天上海的天气真好!我的心情非常高兴!如果去旅游的话我会非常兴奋!和你一起去旅游我会更加幸福!'
data2= '今天上海天气真差,非常讨厌下雨,把我冻坏了,心情太不高兴了,不高兴,我真的很生气!'
data3= '美国华裔科学家,祖籍江苏扬州市高邮县,生于上海,斯坦福大学物理系,电子工程系和应用物理系终身教授!'2、输出结果
很明显,data1情感更加积极!data2情感消极!data3情感中等![[240.0, 104.0, 8.3, 3.6, 8.0, 2.4]]
[[0.0, 134.0, 0.0, 4.8, 0.0, 3.2]]
[[2, 66, 0.1, 3.3, 0.4, 1.7]]
[[2, 2, 0.1, 0.1, 0.4, 0.4]]设计思路
后期更新……
相关资料
1、关于代码
NLP之情感分析:基于python编程(jieba库)实现中文文本情感分析(得到的是情感评分)之全部代码
2、关于数据集
如需数据集,请留言向博主索取。
注:当前为学生身份的网友,可留言向博主索取。非学生身份的社会人士,请靠积分下载!关于留言
1、留言内容的注意事项
- 1、请新增评论,不要直接回复,折叠后,我容易看不到,会漏掉。
- 2、请在前缀加一个索取资料的当天日期。
- 3、切记要留下邮箱!!!
比如留言:“20200307,早上10.11,你好,博主,我的邮箱是,我想索取……”
2、如何留言?2.1、第一种方法——在对应的博客下留言
即在本博客下直接留言即可!
2.2、备用第二种方法——论坛发帖
在我的论坛中发帖即可,我会及时回复。
地址:https://bbs.csdn.net/topics/395531480后续补充发放资料的说明
此类网友,太伤人心,这位网友,一定不是大学生,当代大学生的素质肯定比这位网友高的多。
主要部分代码实现
import jieba import numpy as np …… def sentiment_score_list(dataset): seg_sentence = dataset.split('。') count1 = [] count2 = [] for sen in seg_sentence: #循环遍历每一个评论 segtmp = jieba.lcut(sen, cut_all=False) #把句子进行分词,以列表的形式返回 i = 0 #记录扫描到的词的位置 a = 0 #记录情感词的位置 poscount = 0 #积极词的第一次分值 poscount2 = 0 #积极词反转后的分值 poscount3 = 0 #积极词的最后分值(包括叹号的分值) negcount = 0 negcount2 = 0 negcount3 = 0 for word in segtmp: if word in posdict: # 判断词语是否是情感词 poscount += 1 c = 0 for w in segtmp[a:i]: # 扫描情感词前的程度词 if w in mostdict: poscount *= 4.0 elif w in verydict: poscount *= 3.0 elif w in moredict: poscount *= 2.0 elif w in ishdict: poscount *= 0.5 elif w in deny_word: c += 1 if judgeodd(c) == 'odd': # 扫描情感词前的否定词数 poscount *= -1.0 poscount2 += poscount poscount = 0 poscount3 = poscount + poscount2 + poscount3 poscount2 = 0 else: poscount3 = poscount + poscount2 + poscount3 poscount = 0 a = i + 1 # 情感词的位置变化 elif word in negdict: # 消极情感的分析,与上面一致 negcount += 1 d = 0 for w in segtmp[a:i]: if w in mostdict: negcount *= 4.0 elif w in verydict: negcount *= 3.0 elif w in moredict: negcount *= 2.0 elif w in ishdict: negcount *= 0.5 elif w in degree_word: d += 1 if judgeodd(d) == 'odd': negcount *= -1.0 negcount2 += negcount negcount = 0 negcount3 = negcount + negcount2 + negcount3 negcount2 = 0 else: negcount3 = negcount + negcount2 + negcount3 negcount = 0 a = i + 1 elif word == '!' or word == '!': ##判断句子是否有感叹号 for w2 in segtmp[::-1]: # 扫描感叹号前的情感词,发现后权值+2,然后退出循环 if w2 in posdict or negdict: poscount3 += 2 negcount3 += 2 break i += 1 # 扫描词位置前移 # 以下是防止出现负数的情况 pos_count = 0 neg_count = 0 if poscount3 < 0 and negcount3 > 0: neg_count += negcount3 - poscount3 pos_count = 0 elif negcount3 < 0 and poscount3 > 0: pos_count = poscount3 - negcount3 neg_count = 0 elif poscount3 < 0 and negcount3 < 0: neg_count = -poscount3 pos_count = -negcount3 else: pos_count = poscount3 neg_count = negcount3 count1.append([pos_count, neg_count]) count2.append(count1) count1 = [] return count2 def sentiment_score(senti_score_list): score = [] for review in senti_score_list: score_array = np.array(review) Pos = np.sum(score_array[:, 0]) Neg = np.sum(score_array[:, 1]) AvgPos = np.mean(score_array[:, 0]) AvgPos = float('%.1f'%AvgPos) AvgNeg = np.mean(score_array[:, 1]) AvgNeg = float('%.1f'%AvgNeg) StdPos = np.std(score_array[:, 0]) StdPos = float('%.1f'%StdPos) StdNeg = np.std(score_array[:, 1]) StdNeg = float('%.1f'%StdNeg) score.append([Pos, Neg, AvgPos, AvgNeg, StdPos, StdNeg]) return score data1= '今天上海的天气真好!我的心情非常高兴!如果去旅游的话我会非常兴奋!和你一起去旅游我会更加幸福!' data2= '今天上海天气真差,非常讨厌下雨,把我冻坏了,心情太不高兴了,不高兴,我真的很生气!' data3= '美国华裔科学家,祖籍江苏扬州市高邮县,生于上海,斯坦福大学物理系,电子工程系和应用物理系终身教授!' print(sentiment_score(sentiment_score_list(data1))) print(sentiment_score(sentiment_score_list(data2))) print(sentiment_score(sentiment_score_list(data3)))
-
情感分析
2019-12-09 11:56:21情感分析 自然语言处理(NLP) 将自然语言(文本)转化为计算机程序更容易理解的形式 预处理得到的字符串 -> 向量化 经典应用 情感分析 文本相似度 文本分类 简单的情感分析 情感字典(sentiment dictionary) 人工...情感分析
自然语言处理(NLP)
将自然语言(文本)转化为计算机程序更容易理解的形式预处理得到的字符串 -> 向量化
经典应用
情感分析
文本相似度
文本分类
简单的情感分析
情感字典(sentiment dictionary)人工构造一个字典,如:like -> 1, good -> 2, bad -> -1, terrible-> -2
根据关键词匹配
如 AFINN-111: http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6010,虽简单粗暴,但很实用
问题:
遇到新词,特殊词等,扩展性较差
使用机器学习模型,nltk.classify
-
基于Python的情感分析案例
2018-01-09 12:52:18情感分析:又称为倾向性分析和意见挖掘,它是对带有情感色彩的主观性文本进行分析、处理、归纳和推理的过程,其中情感分析还可以细分为情感极性(倾向)分析,情感程度分析,主客观分析等。 情感极性分析的目的是对...**情感分析:**又称为倾向性分析和意见挖掘,它是对带有情感色彩的主观性文本进行分析、处理、归纳和推理的过程,其中情感分析还可以细分为情感极性(倾向)分析,情感程度分析,主客观分析等。
情感极性分析的目的是对文本进行褒义、贬义、中性的判断。在大多应用场景下,只分为两类。例如对于“喜爱”和“厌恶”这两个词,就属于不同的情感倾向。
**背景交代:**爬虫京东商城某一品牌红酒下所有评论,区分好评和差评,提取特征词,用以区分新的评论【出现品牌名称可以忽视,本文章不涉及打广告哦 o(╯□╰)o】。
示例1(好评)
示例2(差评)
读取文本文件
def text(): f1 = open('E:/工作文件/情感分析案例1/good.txt','r',encoding='utf-8') f2 = open('E:/工作文件/情感分析案例1/bad.txt','r',encoding='utf-8') line1 = f1.readline() line2 = f2.readline() str = '' while line1: str += line1 line1 = f1.readline() while line2: str += line2 line2 = f2.readline() f1.close() f2.close() return str
把单个词作为特征
def bag_of_words(words): return dict([(word,True) for word in words]) print(bag_of_words(text()))
import nltk from nltk.collocations import BigramCollocationFinder from nltk.metrics import BigramAssocMeasures
把双个词作为特征,并使用卡方统计的方法,选择排名前1000的双词
def bigram(words,score_fn=BigramAssocMeasures.chi_sq,n=1000): bigram_finder=BigramCollocationFinder.from_words(words) #把文本变成双词搭配的形式 bigrams = bigram_finder.nbest(score_fn,n) #使用卡方统计的方法,选择排名前1000的双词 newBigrams = [u+v for (u,v) in bigrams] return bag_of_words(newBigrams) print(bigram(text(),score_fn=BigramAssocMeasures.chi_sq,n=1000))
把单个词和双个词一起作为特征
def bigram_words(words,score_fn=BigramAssocMeasures.chi_sq,n=1000): bigram_finder=BigramCollocationFinder.from_words(words) bigrams = bigram_finder.nbest(score_fn,n) newBigrams = [u+v for (u,v) in bigrams] a = bag_of_words(words) b = bag_of_words(newBigrams) a.update(b) #把字典b合并到字典a中 return a print(bigram_words(text(),score_fn=BigramAssocMeasures.chi_sq,n=1000))
结巴分词工具进行分词及词性标注
三种分词模式 :
A、精确模式:试图将句子最精确地切开,适合文本分析。默认是精确模式。
B、全模式:把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不能解决歧义
C、搜索引擎模式:在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词
注:当指定jieba.cut的参数HMM=True时,就有了新词发现的能力。import jieba def read_file(filename): stop = [line.strip() for line in open('E:/工作文件/情感分析案例1/stop.txt','r',encoding='utf-8').readlines()] #停用词 f = open(filename,'r',encoding='utf-8') line = f.readline() str = [] while line: s = line.split('\t') fenci = jieba.cut(s[0],cut_all=False) #False默认值:精准模式 str.append(list(set(fenci)-set(stop))) line = f.readline() return str
安装nltk,pip3 install nltk
from nltk.probability import FreqDist,ConditionalFreqDist from nltk.metrics import BigramAssocMeasures
获取信息量最高(前number个)的特征(卡方统计)
def jieba_feature(number): posWords = [] negWords = [] for items in read_file('E:/工作文件/情感分析案例1/good.txt'):#把集合的集合变成集合 for item in items: posWords.append(item) for items in read_file('E:/工作文件/情感分析案例1/bad.txt'): for item in items: negWords.append(item) word_fd = FreqDist() #可统计所有词的词频 cond_word_fd = ConditionalFreqDist() #可统计积极文本中的词频和消极文本中的词频 for word in posWords: word_fd[word] += 1 cond_word_fd['pos'][word] += 1 for word in negWords: word_fd[word] += 1 cond_word_fd['neg'][word] += 1 pos_word_count = cond_word_fd['pos'].N() #积极词的数量 neg_word_count = cond_word_fd['neg'].N() #消极词的数量 total_word_count = pos_word_count + neg_word_count word_scores = {}#包括了每个词和这个词的信息量 for word, freq in word_fd.items(): pos_score = BigramAssocMeasures.chi_sq(cond_word_fd['pos'][word], (freq, pos_word_count), total_word_count) #计算积极词的卡方统计量,这里也可以计算互信息等其它统计量 neg_score = BigramAssocMeasures.chi_sq(cond_word_fd['neg'][word], (freq, neg_word_count), total_word_count) word_scores[word] = pos_score + neg_score #一个词的信息量等于积极卡方统计量加上消极卡方统计量 best_vals = sorted(word_scores.items(), key=lambda item:item[1], reverse=True)[:number] #把词按信息量倒序排序。number是特征的维度,是可以不断调整直至最优的 best_words = set([w for w,s in best_vals]) return dict([(word, True) for word in best_words])
调整设置,分别从四种特征选取方式开展并比较效果
def build_features(): #feature = bag_of_words(text())#第一种:单个词 #feature = bigram(text(),score_fn=BigramAssocMeasures.chi_sq,n=500)#第二种:双词 #feature = bigram_words(text(),score_fn=BigramAssocMeasures.chi_sq,n=500)#第三种:单个词和双个词 feature = jieba_feature(300)#第四种:结巴分词 posFeatures = [] for items in read_file('E:/工作文件/情感分析案例1/good.txt'): a = {} for item in items: if item in feature.keys(): a[item]='True' posWords = [a,'pos'] #为积极文本赋予"pos" posFeatures.append(posWords) negFeatures = [] for items in read_file('E:/工作文件/情感分析案例1/bad.txt'): a = {} for item in items: if item in feature.keys(): a[item]='True' negWords = [a,'neg'] #为消极文本赋予"neg" negFeatures.append(negWords) return posFeatures,negFeatures
获得训练数据
posFeatures,negFeatures = build_features()
from random import shuffle shuffle(posFeatures) shuffle(negFeatures) #把文本的排列随机化 train = posFeatures[300:]+negFeatures[300:]#训练集(70%) test = posFeatures[:300]+negFeatures[:300]#验证集(30%) data,tag = zip(*test)#分离测试集合的数据和标签,便于验证和测试
def score(classifier): classifier = SklearnClassifier(classifier) classifier.train(train) #训练分类器 pred = classifier.classify_many(data) #给出预测的标签 n = 0 s = len(pred) for i in range(0,s): if pred[i]==tag[i]: n = n+1 return n/s #分类器准确度
这里需要安装几个模块:scipy、numpy、sklearn
scipy及numpy模块需要访问http://www.lfd.uci.edu/~gohlke/pythonlibs,找到scipy、numpy,下载对应版本的whlimport sklearn from nltk.classify.scikitlearn import SklearnClassifier from sklearn.svm import SVC, LinearSVC, NuSVC from sklearn.naive_bayes import MultinomialNB, BernoulliNB from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score
print('BernoulliNB`s accuracy is %f' %score(BernoulliNB())) print('MultinomiaNB`s accuracy is %f' %score(MultinomialNB())) print('LogisticRegression`s accuracy is %f' %score(LogisticRegression())) print('SVC`s accuracy is %f' %score(SVC())) print('LinearSVC`s accuracy is %f' %score(LinearSVC())) print('NuSVC`s accuracy is %f' %score(NuSVC()))
检测结果输出1(单个词:每个字为特征)
检测结果输出2(词[俩字]:2个字为特征,使用卡方统计选取前n个信息量大的作为特征)
检测结果输出3(单个词和双词:把前面2种特征合并之后的特征)
检测结果输出4(结巴分词:用结巴分词外加卡方统计选取前n个信息量大的作为特征)
对比四种特征选取方式可以看出,单字 - 词 - 单字+词 - 结巴分词,效果是越来越好的。
-
情感分析情感分析.zip
2020-05-14 22:13:24SentimentAnalysisDic情感分析
-
WPS Office.10.1.0.6445(有联网功能)_2.7z
-
JavaEE框架(Maven+SSM)全程实战开发教程(源码+讲义)
-
满足低调之心基础十五
-
【2021】UI自动化测试Selenium3
-
Linux图形化界面的安装与卸载
-
selenium学习之处理HTML5视频播放
-
flutter插件调用APP页面、使用原生aar,framework库
-
手势解锁-canvas-javascript实战
-
算法导论二(排序和顺序统计量)——编程大牛的必经之路
-
Java Web开发之Java语言基础
-
2021-01-23
-
论文解读:Factorization Machine(FM)
-
边界布局管理器
-
Mysql实验内容.pdf
-
Unity游戏开发之数字华容道
-
echartsMap.zip
-
xiao4分析题背诵版.pdf
-
5号锂电池对比
-
商业的本质——杰克·韦尔奇著
-
Qt and Qt Charts