Python——对淘宝评论词频统计并生成词云图

9279273-bca628de68d898a6.png
flowerplus的天猫评论,大概300条数据
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 29 13:56:40 2018

@author: Shirley
"""
import xlrd#读取excel
from openpyxl import load_workbook#写入excel
from wordcloud import WordCloud as wd#词云
import jieba#结巴分词
import matplotlib.pyplot as plt#绘图
from collections import defaultdict#字典,用于词频统计
from PIL import Image#打开图片,用于词云背景层
import numpy as np#转换图片,用于词云背景层

path = 'D:/anaconda/shirleylearn/cipintongji/mywordexample.xlsx'#要分词的内容路径
exfile = xlrd.open_workbook(path)#打开excel
sheet1 = exfile.sheet_by_name('Sheet1')#读取Sheet1的内容,根据实际情况填写表名

n = sheet1.nrows#表的总行数
mytext = ''
for i in range(1,n):
    text = sheet1.row(i)[1].value#从第0行开始计数,第0行是栏目,第1行是要的内容
    mytext = mytext+" "+text#把每一天内容合并到一个str中
    
#print(mytext)
'''
mytext = ' '.join(jieba.cut(mytext))

#直接根据分词结果生成简单的词云图
wordcloud = wd(font_path="simsun.ttf").generate(mytext)
plt.imshow(wordcloud,interpolation='bilinear')
plt.axis('off')#不显示坐标轴 
'''
jieba.add_word('洋桔梗')#默认把“洋”和“桔梗”分开了,这里加新词,使分词结果更准确
jieba.add_word('洋牡丹')#花毛莨又名洋牡丹,很漂亮O(∩_∩)O
jieba.add_word('花加')#如果新词多的话,可以用自己的词库进行分词,在搜狗输入法的网站上有很多分类词库
mytext = jieba.lcut(mytext)#把分词结果生成为列表
#print(mytext)

sl = []
with open('D:/anaconda/shirleylearn/cipintongji/stopwords.txt','r') as f:#打开停用词文件
    s = f.readlines()
    for a in s:
        a = a.replace('\n','')
        sl.append(a)#把停用词存入列表
        
sl.append('\u200b')
sl.append('\xa0')#这2个符号无法通过stopwords去除,只能在这里增加到列表中,不知道有没有更好的办法

wordfrequency = defaultdict(int)
for word in mytext:
    if word not in sl:#去停用词
        wordfrequency[word] += 1#词频统计

#print(wordfrequency)
        
img = Image.open("D:/anaconda/shirleylearn/cipintongji/bgimg_rose.jpg")#打开图片
myimg = np.array(img)#转换图片


wordcloud = wd(width=1000,height=860,margin=2,font_path="simsun.ttf",background_color="white",max_font_size=180,mask = myimg).fit_words(wordfrequency)#根据词频字典生成词云
plt.imshow(wordcloud)
plt.axis('off')#不显示坐标轴 
plt.savefig('wc_flowerplus.png', dpi=300)#存储图片,dpi就是每英寸里有多少个点,点越多就越清晰。

file = load_workbook(path)#打开excel
nsheet = file.create_sheet('frequency',index=0)#新建表
nsheet.cell(1,1,'word')#写入表头
nsheet.cell(1,2,'frequency')#写入表头

wordfrequency_order = sorted(wordfrequency.items(),key = lambda x:x[1],reverse = True)#把字典按词频降序排列

for n in range(2,len(wordfrequency_order)+2):#把降序后的词频统计结果写入excel
    nsheet.cell(n,1,wordfrequency_order[n-2][0])
    nsheet.cell(n,2,wordfrequency_order[n-2][1])

file.save(path)
9279273-9d8970d7e45ca0f6.png
词频统计结果

可以检查下分词有没有问题,我在结巴分词中增加了2个花卉的名称和“花加”这品牌名,如果要求严格的话最好把单个的词都检查一下,不要的可以去除,比如“挺”这个字出现的频率很高,在评论中的搭配是“挺好的”、“挺满意”。


9279273-caf433d6f893903b.png
最后生成的词云图,看得出来是朵花的形状吗(〃'▽'〃)

PS:在选择背景图片时,不要选择内存太大的,20K上下,色彩边界清晰的就行,一开始我用了一张500K左右的图,程序运行了好久,我以为是代码出问题了,而且生成的图片上字超级小。

猜你喜欢

转载自blog.csdn.net/weixin_33932129/article/details/87232019