首页 > 其他分享 >评论数据分析

评论数据分析

时间:2023-04-03 16:35:48浏览次数:24  
标签:数据分析 index word type content 评论 result data

# -*- coding: utf-8 -*-

# 代码12-1 评论去重的代码

import pandas as pd
import re
import jieba.posseg as psg
import numpy as np


# 去重,去除完全重复的数据
reviews = pd.read_csv("C:/Users/admin/Downloads/data/reviews.csv")
reviews = reviews[['content', 'content_type']].drop_duplicates()
content = reviews['content']

 

# 代码12-2 数据清洗

# 去除去除英文、数字等
# 由于评论主要为京东美的电热水器的评论,因此去除这些词语
strinfo = re.compile('[0-9a-zA-Z]|京东|美的|电热水器|热水器|')
content = content.apply(lambda x: strinfo.sub('', x))

 

# 代码12-3 分词、词性标注、去除停用词代码

# 分词
worker = lambda s: [(x.word, x.flag) for x in psg.cut(s)] # 自定义简单分词函数
seg_word = content.apply(worker)

# 将词语转为数据框形式,一列是词,一列是词语所在的句子ID,最后一列是词语在该句子的位置
n_word = seg_word.apply(lambda x: len(x)) # 每一评论中词的个数

n_content = [[x+1]*y for x,y in zip(list(seg_word.index), list(n_word))]
index_content = sum(n_content, []) # 将嵌套的列表展开,作为词所在评论的id

seg_word = sum(seg_word, [])
word = [x[0] for x in seg_word] # 词

nature = [x[1] for x in seg_word] # 词性

content_type = [[x]*y for x,y in zip(list(reviews['content_type']), list(n_word))]
content_type = sum(content_type, []) # 评论类型

result = pd.DataFrame({"index_content":index_content,
"word":word,
"nature":nature,
"content_type":content_type})

# 删除标点符号
result = result[result['nature'] != 'x'] # x表示标点符号

# 删除停用词
stop_path = open("C:/Users/admin/Downloads/data/stoplist.txt", 'r',encoding='UTF-8')
stop = stop_path.readlines()
stop = [x.replace('\n', '') for x in stop]
word = list(set(word) - set(stop))
result = result[result['word'].isin(word)]

# 构造各词在对应评论的位置列
n_word = list(result.groupby(by = ['index_content'])['index_content'].count())
index_word = [list(np.arange(0, y)) for y in n_word]
index_word = sum(index_word, []) # 表示词语在改评论的位置

# 合并评论id,评论中词的id,词,词性,评论类型
result['index_word'] = index_word

 


# 代码12-4 提取含有名词的评论

# 提取含有名词类的评论
ind = result[['n' in x for x in result['nature']]]['index_content'].unique()
result = result[[x in ind for x in result['index_content']]]

 

# 代码12-5 绘制词云

import matplotlib.pyplot as plt
from wordcloud import WordCloud

frequencies = result.groupby(by = ['word'])['word'].count()
frequencies = frequencies.sort_values(ascending = False)
backgroud_Image=plt.imread('C:/Users/admin/Downloads/data/pl.jpg')
wordcloud = WordCloud(font_path=r"C:/Windows/Fonts/Arial.ttf",
max_words=100,
background_color='white',
mask=backgroud_Image)
my_wordcloud = wordcloud.fit_words(frequencies)
plt.imshow(my_wordcloud)
plt.axis('off')
plt.show()
print('okkkkkk')
# 将结果写出
result.to_csv("C:/Users/admin/Downloads/data/word1.csv", index = False, encoding = 'utf-8')
print('11111111111')

import numpy as np
# 分词
worker = lambda s: [(x.word, x.flag) for x in psg.cut(s)] # 自定义简单分词函数
seg_word = content.apply(worker)

# 将词语转为数据框形式,一列是词,一列是词语所在的句子ID,最后一列是词语在该句子的位置
n_word = seg_word.apply(lambda x: len(x)) # 每一评论中词的个数

n_content = [[x+1]*y for x,y in zip(list(seg_word.index), list(n_word))]
index_content = sum(n_content, []) # 将嵌套的列表展开,作为词所在评论的id

seg_word = sum(seg_word, [])
word = [x[0] for x in seg_word] # 词

nature = [x[1] for x in seg_word] # 词性

content_type = [[x]*y for x,y in zip(list(reviews['content_type']),
list(n_word))]
content_type = sum(content_type, []) # 评论类型

result = pd.DataFrame({"index_content":index_content,
"word":word,
"nature":nature,
"content_type":content_type})

# 删除标点符号
result = result[result['nature'] != 'x'] # x表示标点符号

# 删除停用词
stop_path = open(r"C:\Users\admin\Downloads\data\stoplist.txt", 'r',encoding='UTF-8')
stop = stop_path.readlines()
stop = [x.replace('\n', '') for x in stop]
word = list(set(word) - set(stop))
result = result[result['word'].isin(word)]

# 构造各词在对应评论的位置列
n_word = list(result.groupby(by = ['index_content'])['index_content'].count())
index_word = [list(np.arange(0, y)) for y in n_word]
index_word = sum(index_word, []) # 表示词语在改评论的位置

# 合并评论id,评论中词的id,词,词性,评论类型
result['index_word'] = index_word

 

# 代码12-4

# 提取含有名词类的评论
ind = result[['n' in x for x in result['nature']]]['index_content'].unique()
result = result[[x in ind for x in result['index_content']]]

 

# 代码12-5

import matplotlib.pyplot as plt
from wordcloud import WordCloud

frequencies = result.groupby(by = ['word'])['word'].count()
frequencies = frequencies.sort_values(ascending = False)
backgroud_Image=plt.imread(r'C:\Users\admin\Downloads\data/pl.jpg')
wordcloud = WordCloud(font_path=r"C:/Windows/Fonts/Arial.ttf",
max_words=100,
background_color='white',
mask=backgroud_Image)
my_wordcloud = wordcloud.fit_words(frequencies)
plt.imshow(my_wordcloud)
plt.axis('off')
plt.show()

# 将结果写出
result.to_csv("../word1.csv", index = False, encoding = 'utf-8')

# -*- coding: utf-8 -*-

# 代码12-6 匹配情感词

import pandas as pd
import numpy as np
word = pd.read_csv("../word1.csv")

# 读入正面、负面情感评价词
pos_comment = pd.read_csv(r"C:/Users/admin/Downloads/data/正面评价词语(中文).txt", header=None,sep="/n", 
                          encoding = 'utf-8', engine='python')
neg_comment = pd.read_csv(r"C:/Users/admin/Downloads/data/负面评价词语(中文).txt", header=None,sep="/n", 
                          encoding = 'utf-8', engine='python')
pos_emotion = pd.read_csv(r"C:/Users/admin/Downloads/data/正面情感词语(中文).txt", header=None,sep="/n", 
                          encoding = 'utf-8', engine='python')
neg_emotion = pd.read_csv(r"C:/Users/admin/Downloads/data/负面情感词语(中文).txt", header=None,sep="/n", 
                          encoding = 'utf-8', engine='python') 

# 合并情感词与评价词
positive = set(pos_comment.iloc[:,0])|set(pos_emotion.iloc[:,0])
negative = set(neg_comment.iloc[:,0])|set(neg_emotion.iloc[:,0])
intersection = positive&negative  # 正负面情感词表中相同的词语
positive = list(positive - intersection)
negative = list(negative - intersection)
positive = pd.DataFrame({"word":positive,
                         "weight":[1]*len(positive)})
negative = pd.DataFrame({"word":negative,
                         "weight":[-1]*len(negative)}) 

posneg = positive.append(negative)

#  将分词结果与正负面情感词表合并,定位情感词
data_posneg = posneg.merge(word, left_on = 'word', right_on = 'word', 
                           how = 'right')
data_posneg = data_posneg.sort_values(by = ['index_content','index_word'])



# 代码12-7 修正情感倾向

# 根据情感词前时候有否定词或双层否定词对情感值进行修正
# 载入否定词表
notdict = pd.read_csv("C:/Users/admin/Downloads/data/not.csv")

# 处理否定修饰词
data_posneg['amend_weight'] = data_posneg['weight']  # 构造新列,作为经过否定词修正后的情感值
data_posneg['id'] = np.arange(0, len(data_posneg))
only_inclination = data_posneg.dropna()  # 只保留有情感值的词语
only_inclination.index = np.arange(0, len(only_inclination))
index = only_inclination['id']

for i in np.arange(0, len(only_inclination)):
    review = data_posneg[data_posneg['index_content'] == 
                         only_inclination['index_content'][i]]  # 提取第i个情感词所在的评论
    review.index = np.arange(0, len(review))
    affective = only_inclination['index_word'][i]  # 第i个情感值在该文档的位置
    if affective == 1:
        ne = sum([i in notdict['term'] for i in review['word'][affective - 1]])
        if ne == 1:
            data_posneg['amend_weight'][index[i]] = -\
            data_posneg['weight'][index[i]]          
    elif affective > 1:
        ne = sum([i in notdict['term'] for i in review['word'][[affective - 1, 
                  affective - 2]]])
        if ne == 1:
            data_posneg['amend_weight'][index[i]] = -\
            data_posneg['weight'][index[i]]
            
# 更新只保留情感值的数据
only_inclination = only_inclination.dropna()

# 计算每条评论的情感值
emotional_value = only_inclination.groupby(['index_content'],
                                           as_index=False)['amend_weight'].sum()

# 去除情感值为0的评论
emotional_value = emotional_value[emotional_value['amend_weight'] != 0]



# 代码12-8 查看情感分析效果

# 给情感值大于0的赋予评论类型(content_type)为pos,小于0的为neg
emotional_value['a_type'] = ''
emotional_value['a_type'][emotional_value['amend_weight'] > 0] = 'pos'
emotional_value['a_type'][emotional_value['amend_weight'] < 0] = 'neg'

# 查看情感分析结果
result = emotional_value.merge(word, 
                               left_on = 'index_content', 
                               right_on = 'index_content',
                               how = 'left')

result = result[['index_content','content_type', 'a_type']].drop_duplicates() 
confusion_matrix = pd.crosstab(result['content_type'], result['a_type'], 
                               margins=True)  # 制作交叉表
(confusion_matrix.iat[0,0] + confusion_matrix.iat[1,1])/confusion_matrix.iat[2,2]

# 提取正负面评论信息
ind_pos = list(emotional_value[emotional_value['a_type'] == 'pos']['index_content'])
ind_neg = list(emotional_value[emotional_value['a_type'] == 'neg']['index_content'])
posdata = word[[i in ind_pos for i in word['index_content']]]
negdata = word[[i in ind_neg for i in word['index_content']]]

# 绘制词云
import matplotlib.pyplot as plt
from wordcloud import WordCloud
# 正面情感词词云
freq_pos = posdata.groupby(by = ['word'])['word'].count()
freq_pos = freq_pos.sort_values(ascending = False)
backgroud_Image=plt.imread('C:/Users/admin/Downloads/data/pl.jpg')
wordcloud = WordCloud(font_path="C:/Windows/Fonts/Arial.ttf",
                      max_words=100,
                      background_color='white',
                      mask=backgroud_Image)
pos_wordcloud = wordcloud.fit_words(freq_pos)
plt.imshow(pos_wordcloud)
plt.axis('off') 
plt.show()
# 负面情感词词云
freq_neg = negdata.groupby(by = ['word'])['word'].count()
freq_neg = freq_neg.sort_values(ascending = False)
neg_wordcloud = wordcloud.fit_words(freq_neg)
plt.imshow(neg_wordcloud)
plt.axis('off') 
plt.show()

# 将结果写出,每条评论作为一行
posdata.to_csv("C:/Users/admin/Downloads/data/posdata.csv", index = False, encoding = 'utf-8')
negdata.to_csv("C:/Users/admin/Downloads/data/negdata.csv", index = False, encoding = 'utf-8')

 

标签:数据分析,index,word,type,content,评论,result,data
From: https://www.cnblogs.com/3045qqq/p/17283440.html

相关文章

  • 数据分析-字词云
    数据预处理#代码12-1评论去重的代码importpandasaspdimportre#正则匹配importjieba.possegaspsgimportnumpyasnp#去重,去除完全重复的数据reviews=pd.read_csv("D:/人工智能&软件工程/数据挖掘与分析/dem......
  • 数据分析之电子商务网站用户行为分析及服务推荐
    01-mysql_access.py1#-*-coding:utf-8-*-23#代码11-145importos6importpandasaspd789#修改工作路径到指定文件夹10os.chdir("D:/chapter11/demo")1112#第一种连接方式13fromsqlalchemyimportcreate_engine1415engine=cre......
  • 第六周数据分析实训
    importosimportpandasaspd#修改工作路径到指定文件夹os.chdir("E:/桌面/data")#第一种连接方式fromsqlalchemyimportcreate_engineengine=create_engine('mysql+pymysql://root:123456@localhost:3306/sx5?charset=utf8')sql=pd.read_sql('all_gz......
  • 【Pandas数据处理100例目录】Python数据分析玩转Excel表格数据
    前言大家好,我是阿光。本专栏整理了《Pandas数据分析处理》,内包含了各种常见的数据处理,以及Pandas内置函数的使用方法,帮助我们快速便捷的处理表格数据。正在更新中~✨......
  • Linux数据分析之九个给力的命令行工具
    导读要对数据进行分析,大家会从哪里入手?对于大多数熟悉了图形工作环境的朋友来说,电子表格工具无疑是第一选项。但命令行工具同样能够更快更高效地解决问题——且只须稍微学习即可上手。要对数据进行分析,大家会从哪里入手?对于大多数熟悉了图形工作环境的朋友来说,电子表......
  • 家用热水器数据分析
    importpandasaspdimportmatplotlib.pyplotaspltinputfile=r'E:\python数据分析\Python数据分析与挖掘实战(第2版)\chapter10\demo\data/original_data.xls'#输入的数据文件data=pd.read_excel(inputfile)#读取数据#查看有无水流的分布#数据提取lv_non=......
  • R数据分析:生存分析的列线图的理解与绘制详细教程
    列线图作为一个非常简单明了的临床辅助决策工具,在临床中用的(发文章的)还是比较多的,尤其是肿瘤预后:Nomogramsarewidelyusedforcancerprognosis,primarilybecauseoftheirabilitytoreducestatisticalpredictivemodelsintoasinglenumericalestimateoftheprob......
  • 数据分析6
    importosimportpandasaspd#修改工作路径到指定文件夹os.chdir("E:/demo")##第一种连接方式#fromsqlalchemyimportcreate_engine#engine=create_engine('m......
  • 零售数据分析之操作篇10:销售排名与TOP分析
    各位数据的朋友,大家好,我是老周道数据,和你一起,用常人思维+数据分析,通过数据讲故事。上期回顾与作业解答上一讲讲了如何通过历史聚合与其他聚合一起使用的场景,包括历史聚合+唯......
  • R语言泰坦尼克号随机森林模型案例数据分析|附代码数据
    原文链接:http://tecdat.cn/?p=4281最近我们被客户要求撰写关于随机森林模型的研究报告,包括一些图形和统计输出。如果我们对所有这些模型的结果进行平均,我们有时可以从它......