python 爬取京东指定商品评论并进行情感分析


Posted in Python onMay 27, 2021

项目地址

https://github.com/DA1YAYUAN/JD-comments-sentiment-analysis

爬取京东商城中指定商品下的用户评论,对数据预处理后基于SnowNLP的sentiment模块对文本进行情感分析。

运行环境

  • Mac OS X
  • Python3.7 requirements.txt
  • Pycharm

运行方法

数据爬取(jd.comment.py)

  1. 启动jd_comment.py,建议修改jd_comment.py中变量user-agent为自己浏览器用户代理
  2. 输入京东商品完整URL
  3. 得到京东评论词云,存放于jd_ciyun.jpg(词云轮廓形状存放于jdicon.jpg)
  4. 得到京东评论数据,存放于jd_comment.csv
import os
import time
import json
import random
import csv
import re

import jieba
import requests
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from wordcloud import WordCloud

# 词云形状图片
WC_MASK_IMG = 'jdicon.jpg'
# 评论数据保存文件
COMMENT_FILE_PATH = 'jd_comment.txt'
# 词云字体
WC_FONT_PATH = '/Library/Fonts/Songti.ttc'


def spider_comment(page=0, key=0):
    """
    爬取京东指定页的评价数据
    :param page: 爬取第几,默认值为0
    """

    url = 'https://club.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98vv4646&productId=' + key + '' \
          '&score=0&sortType=5&page=%s&pageSize=10&isShadowSku=0&fold=1' % page
    kv = {'user-agent': 'Mozilla/5.0', 'Referer': 'https://item.jd.com/'+ key + '.html'}#原本key不输入值,默认为《三体》

    try:
        r = requests.get(url, headers=kv)
        r.raise_for_status()
    except:
        print('爬取失败')
    # 截取json数据字符串
    r_json_str = r.text[26:-2]
    # 字符串转json对象
    r_json_obj = json.loads(r_json_str)
    # 获取评价列表数据
    r_json_comments = r_json_obj['comments']
    # 遍历评论对象列表
    for r_json_comment in r_json_comments:
        # 以追加模式换行写入每条评价
        with open(COMMENT_FILE_PATH, 'a+') as file:
            file.write(r_json_comment['content'] + '\n')
        # 打印评论对象中的评论内容
        print(r_json_comment['content'])


def batch_spider_comment():
    """
        批量爬取某东评价
        """
    # 写入数据前先清空之前的数据
    if os.path.exists(COMMENT_FILE_PATH):
        os.remove(COMMENT_FILE_PATH)
    key = input("Please enter the address:")
    key = re.sub("\D","",key)
    #通过range来设定爬取的页面数
    for i in range(10):
        spider_comment(i,key)
        # 模拟用户浏览,设置一个爬虫间隔,防止ip被封
        time.sleep(random.random() * 5)


def cut_word():
    """
    对数据分词
    :return: 分词后的数据
    """
    with open(COMMENT_FILE_PATH) as file:
        comment_txt = file.read()
        wordlist = jieba.cut(comment_txt, cut_all=False)#精确模式
        wl = " ".join(wordlist)
        print(wl)
        return wl


def create_word_cloud():
    """44144127306
    生成词云
    :return:
    """
    # 设置词云形状图片
    wc_mask = np.array(Image.open(WC_MASK_IMG))
    # 设置词云的一些配置,如:字体,背景色,词云形状,大小
    wc = WordCloud(background_color="white", max_words=2000, mask=wc_mask, scale=4,
                   max_font_size=50, random_state=42, font_path=WC_FONT_PATH)
    # 生成词云
    wc.generate(cut_word())
    # 在只设置mask的情况下,你将会得到一个拥有图片形状的词云
    plt.imshow(wc, interpolation="bilinear")
    plt.axis("off")
    plt.figure()
    plt.show()
    wc.to_file("jd_ciyun.jpg")


def txt_change_to_csv():
    with open('jd_comment.csv', 'w+', encoding="utf8", newline='')as c:
        writer_csv = csv.writer(c, dialect="excel")
        with open("jd_comment.txt", 'r', encoding='utf8')as f:
            # print(f.readlines())
            for line in f.readlines():
                # 去掉str左右端的空格并以空格分割成list
                line_list = line.strip('\n').split(',')
                print(line_list)
                writer_csv.writerow(line_list)

if __name__ == '__main__':
    # 爬取数据
    batch_spider_comment()

    #转换数据
    txt_change_to_csv()

    # 生成词云
    create_word_cloud()

模型训练(train.py)

  1. 准备正负语料集online_shopping_10_cats.csv,分别存入negative.txt和positive.txt
  2. 启动train.py,新建文件sentiment.marshal,存入训练后的模型
  3. 找到外部库中snownlp中sentiment模块,将训练得到的sentiment.marshal.3文件覆盖sentiment模块中自带的sentiment.marshal.3
# -*-coding:utf-8-*-

def train():
    from snownlp import sentiment
    print("开始训练数据集...")
    sentiment.train('negative.txt', 'positive.txt')#自己准备数据集
    sentiment.save('sentiment.marshal')#保存训练模型
    #python2保存的是sentiment.marshal;python3保存的是sentiment.marshal.3
    "训练完成后,将训练完的模型,替换sentiment中的模型"

def main():
    train()  # 训练正负向商品评论数据集
    print("数据集训练完成!")

if __name__ == '__main__':
    main()

情感分析(sentiment.analysis.py)

  1. 启动sentiment.analysis.py
  2. 开始对jd_comment.csv中评论进行数据处理,处理后文件存入processed_comment_data.csv
  3. sentiment模块根据sentiment.marshal.3对评论进行情感评分,评分结果存入result.csv
  4. 评分结果可视化,生成文件fig.png
from snownlp import sentiment
import pandas as pd
import snownlp
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

#from word_cloud import word_cloud_creation, word_cloud_implementation, word_cloud_settings

def read_csv():
    '''读取商品评论数据文件'''
    comment_data = pd.read_csv('jd_comment.csv', encoding='utf-8',
                               sep='\n', index_col=None)
    #返回评论作为参数
    return comment_data


def clean_data(data):
    '''数据清洗'''
    df = data.dropna()  # 消除缺失数据 NaN为缺失数据
    df = pd.DataFrame(df.iloc[:, 0].unique())  # 数据去重
    return df
    # print('数据清洗后:', len(df))


def clean_repeat_word(raw_str, reverse=False):
    '''去除评论中的重复使用的词汇'''
    if reverse:
        raw_str = raw_str[::-1]
    res_str = ''
    for i in raw_str:
        if i not in res_str:
            res_str += i
    if reverse:
        res_str = res_str[::-1]
    return res_str


def processed_data(filename):
    '''清洗完毕的数据,并保存'''
    df = clean_data(read_csv())#数据清洗
    ser1 = df.iloc[:, 0].apply(clean_repeat_word)#去除重复词汇
    df2 = pd.DataFrame(ser1.apply(clean_repeat_word, reverse=True))
    df2.to_csv(f'{filename}.csv', encoding='utf-8', index_label=None, index=None)


def train():
    '''训练正向和负向情感数据集,并保存训练模型'''
    sentiment.train('negative.txt', 'positive.txt')
    sentiment.save('seg.marshal')#python2保存的是sentiment.marshal;python3保存的是sentiment.marshal.3


sentiment_list = []

res_list = []


def test(filename, to_filename):
    '''商品评论-情感分析-测试'''
    with open(f'{filename}.csv', 'r', encoding='utf-8') as fr:
        for line in fr.readlines():
            s = snownlp.SnowNLP(line)
            #调用snownlp中情感评分s.sentiments
            if s.sentiments > 0.6:
                res = '喜欢'
                res_list.append(1)
            elif s.sentiments < 0.4:
                res = '不喜欢'
                res_list.append(-1)
            else:
                res = '一般'
                res_list.append(0)
            sent_dict = {
                '情感分析结果': s.sentiments,
                '评价倾向': res,
                '商品评论': line.replace('\n', '')
            }
            sentiment_list.append(sent_dict)
            print(sent_dict)
        df = pd.DataFrame(sentiment_list)
        df.to_csv(f'{to_filename}.csv', index=None, encoding='utf-8',
                  index_label=None, mode='w')


def data_virtualization():
    '''分析结果可视化,以条形图为测试样例'''
    font = FontProperties(fname='/System/Library/Fonts/Supplemental/Songti.ttc', size=14)
    likes = len([i for i in res_list if i == 1])
    common = len([i for i in res_list if i == 0])
    unlikes = len([i for i in res_list if i == -1])

    plt.bar([1], [likes], label='喜欢')#(坐标,评论长度,名称)
    plt.bar([2], [common], label='一般')
    plt.bar([3], [unlikes], label='不喜欢')

    x=[1,2,3]
    label=['喜欢','一般','不喜欢']
    plt.xticks(x, label)

    plt.legend()#插入图例
    plt.xlabel('评价种类')
    plt.ylabel('评价数目')
    plt.title(u'商品评论情感分析结果-条形图', FontProperties=font)
    plt.savefig('fig.png')
    plt.show()
'''
def word_cloud_show():
    #将商品评论转为高频词汇的词云
    wl = word_cloud_creation('jd_comment.csv')
    wc = word_cloud_settings()
    word_cloud_implementation(wl, wc)
'''

def main():
     processed_data('processed_comment_data')#数据清洗
     #train()  # 训练正负向商品评论数据集

     test('jd_comment', 'result')

     print('数据可视化中...')
     data_virtualization()  # 数据可视化

     print('python程序运行结束。')

if __name__ == '__main__':
    main()

 

词云轮廓图

python 爬取京东指定商品评论并进行情感分析

商品评论词云

python 爬取京东指定商品评论并进行情感分析

情感分析结果可视化

python 爬取京东指定商品评论并进行情感分析

以上就是python 爬取京东指定商品评论并进行情感分析的详细内容,更多关于python 爬取京东评论并进行情感分析的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
从Python的源码浅要剖析Python的内存管理
Apr 16 Python
使用rpclib进行Python网络编程时的注释问题
May 06 Python
在Python中操作文件之truncate()方法的使用教程
May 25 Python
python使用mysql数据库示例代码
May 21 Python
Python闭包之返回函数的函数用法示例
Jan 27 Python
django的settings中设置中文支持的实现
Apr 28 Python
python编写微信公众号首图思路详解
Dec 13 Python
Pytorch基本变量类型FloatTensor与Variable用法
Jan 08 Python
谈一谈数组拼接tf.concat()和np.concatenate()的区别
Feb 07 Python
全网首秀之Pycharm十大实用技巧(推荐)
Apr 27 Python
Python如何脚本过滤文件中的注释
May 27 Python
升级keras解决load_weights()中的未定义skip_mismatch关键字问题
Jun 12 Python
python b站视频下载的五种版本
May 27 #Python
教你怎么用python selenium实现自动化测试
Python Django框架介绍之模板标签及模板的继承
May 27 #Python
python 算法题——快乐数的多种解法
May 27 #Python
用Python监控你的朋友都在浏览哪些网站?
Python图片处理之图片裁剪教程
用Python进行栅格数据的分区统计和批量提取
You might like
PHP中VC6、VC9、TS、NTS版本的区别与用法详解
2013/10/26 PHP
Codeigniter+PHPExcel实现导出数据到Excel文件
2014/06/12 PHP
php实现mysql连接池效果实现代码
2018/01/25 PHP
PHP设计模式之装饰器(装饰者)模式(Decorator)入门与应用详解
2019/12/13 PHP
JS文本框不能输入空格验证方法
2013/03/19 Javascript
jquery uploadify 在FF下无效的解决办法
2014/09/26 Javascript
JavaScript前端图片加载管理器imagepool使用详解
2014/12/29 Javascript
基于jQuery日历插件制作日历
2016/03/11 Javascript
Vue2组件tree实现无限级树形菜单
2017/03/29 Javascript
jQuery插件FusionCharts绘制的2D条状图效果【附demo源码】
2017/05/13 jQuery
解决vue的变量在settimeout内部效果失效的问题
2018/08/30 Javascript
使用pkg打包Node.js应用的方法步骤
2018/10/19 Javascript
JS如何生成动态列表
2020/09/22 Javascript
[01:50]2014DOTA2西雅图邀请赛 专访欢乐周宝龙
2014/07/08 DOTA
python实现简单socket通信的方法
2016/04/19 Python
Python 通过URL打开图片实例详解
2017/06/01 Python
Python使用Matplotlib模块时坐标轴标题中文及各种特殊符号显示方法
2018/05/04 Python
在CMD命令行中运行python脚本的方法
2018/05/12 Python
python print输出延时,让其立刻输出的方法
2019/01/07 Python
pycharm实现在子类中添加一个父类没有的属性
2020/03/12 Python
python+openCV对视频进行截取的实现
2020/11/27 Python
巴西家用小家电购物网站:Polishop
2016/08/07 全球购物
微软香港官网及网上商店:Microsoft HK
2016/09/01 全球购物
Farnell德国:电子元器件供应商
2018/07/10 全球购物
德国圣伯纳德草药屋:Kräuterhaus Sanct Bernhard(有中文站)
2018/08/05 全球购物
Farfetch中文官网:奢侈品牌时尚购物平台
2020/03/15 全球购物
电子商务应届生求职信
2013/11/16 职场文书
还款承诺书范文
2014/05/20 职场文书
相亲活动方案
2014/08/26 职场文书
皇城相府导游词
2015/02/06 职场文书
2015感人爱情寄语
2015/02/26 职场文书
个人简历自我评价怎么写
2015/03/10 职场文书
毕业论文致谢信
2015/05/14 职场文书
孔繁森观后感
2015/06/10 职场文书
浅谈Python数学建模之固定费用问题
2021/06/23 Python
redis 解决库存并发问题实现数量控制
2022/04/08 Redis