Python获取商品评论,制作词云图,进行可视化分析

哈喽大家好,我是巳月,今天我们来试试采集某东电商平台商品评论,制作词云图。

事情是这样的,昨天有个逗比,说没有女朋友,问我学会了Python能有女朋友吗,这我能欺骗他?

Python获取商品评论,制作词云图,进行可视化分析_第1张图片

当然是选择告诉他可以,并用Python给他爬了一个!

Python获取商品评论,制作词云图,进行可视化分析_第2张图片

采集评论

import requests
import time
import re
for page in range(0, 100):
    time.sleep(2)
    url = 'https://为了防止文章被吞,网址我屏蔽了,完整代码获取Q裙592539176/comment/productPageComments.action?callback=fetchJSON_comment98&productId=12520305481&score=0&sortType=5&page={}&pageSize=10&isShadowSku=0&rid=0&fold=1'.format(page)
    headers = {
        'cookie': 'PCSYCityID=CN_0_0_0; jwotest_product=99; areaId=18; ipLoc-djd=18-1482-48936-0; unpl=V2_ZzNtbUtfQUYgCEEEfUtZA2IFEQ5LAxYTcVpOASxLXAJgUBEKclRCFnQURlVnGVQUZwQZWUFcRxVFCEdkeB5fA2AFEFlBZxBFLV0CFi9JH1c%2bbRdZQF5EHHwAQ1R8KWwGZzMSXHJTQhV2DE5RchFsNWAzIm1AVUUUfA92VUsYbEczXxpUS1FLHTgMR1R4HVQAbgsiXHJU; __jdv=76161171|baidu-search|t_262767352_baidusearch|cpc|45386889416_0_893bd16a7c47472b8ed75c9dfc166b2f|1603097572255; __jdu=501259489; shshshfpb=tD5U5kzKI%2FrPwiQKAePBtLQ%3D%3D; shshshfpa=7a29fb15-8ae0-995d-303d-02ced1f37473-1601270653; __jda=122270672.501259489.1603097571.1603097571.1603097572.1; __jdc=122270672; shshshfp=8605b9031ad5da18cc9f19e47d4edcba; 3AB9D23F7A4B3C9B=C6CFZWH3AOQJASJVY4I5ZGKYGRGCYTU4KH4XYGXAXS5MQ3QRIGKR7TSLJWPIMM7X2SE6I6WLMCB5ZIYCYBSOO4KRBI; shshshsID=4596a4a3bf541ff0cee5bb2d2a1d9714_6_1603097694903; __jdb=122270672.6.501259489|1.1603097572; JSESSIONID=F2250FD11DD25985B7572DD293CBDC12.s1',
        'referer': 'https://****/12520305481.html',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
    }
    response = requests.get(url=url, headers=headers)
    html_data = response.content.decode('gbk')
    lis = re.findall('"content":"(.*?)"', response.text, re.S)
    for i in lis:
        with open('商品评论.txt', mode='a', encoding='utf-8') as f:
            f.write(i)
            f.write('\n')
            print(i)

采集结果

算了 ,结果不展示了,我有点害怕,因为咱抓取的内容有点惊世骇俗。

生成词云图

import jieba
import wordcloud
import imageio
# 导入imageio库中的imread函数,并用这个函数读取本地图片,作为词云形状图片
# py = imageio.imread(r"D:\python\demo\某东\timg.png")
# 读取文件内容
f = open(r'D:\python\demo\某东\商品评论.txt', encoding='utf-8')
txt = f.read()
# print(txt)
# jiabe 分词 分割词汇
txt_list = jieba.lcut(txt)
string = ' '.join(txt_list)
# 词云图设置
wc = wordcloud.WordCloud(
        width=1000,         # 图片的宽
        height=700,         # 图片的高
        background_color='white',   # 图片背景颜色
        font_path='msyh.ttc',    # 词云字体
        # mask=py,     # 所使用的词云图片
        scale=15,
        stopwords={'真的', '感觉', '这个', '这个', '这个'},
        # contour_width=5,
        # contour_color='red'  # 轮廓颜色
)
# 给词云输入文字
wc.generate(string)
# 词云图保存图片地址
wc.to_file(r'D:\python\demo\某东\out.png')

词云图效果展示

好了,今天的分享就到这结束了,咱们下次见!

你可能感兴趣的:(Python,python,开发语言)