情感分析

Reads: 885 Edit

1 问题描述

对于网购的评价,既可能存在好评,又可能存在差评。我们这里可以分别将好评的评论内容和差评的评论内容爬取下来,并分别绘制好评和差评的词云,对比差评和好评的词语,从而对购物者的评价进行情感分析。

网购评论中本身存在好评和差评的情感标签。对于一些纯内容的文本(如一篇小说)进行情感分析,则需要借助情感词库来对内容进行统计分,目前这类方法主要受制于情感词库的优劣,这里不再演示。

2 爬取京东商品的评论数据(动态网页)

2.1 获取评论数据的网址

注意:网页评论的地址并不是商品网页的地址,需要采用如下形式获取网址信息。

第一步:打开浏览器的“检查元素”功能,切换到network选项。

r-104

第二步:刷新整个商品网页

第三步:点击页面上的商品评价按钮,然后再点击好评!

r-110-1

第四步:点击“检查元素”工具栏以“productPageComments...”开头的条目(这一步不同购物网站不一样,需要尝试、摸索、寻找)。右侧的Request URL就是商品评价的网络地址信息。可以看到,对于好评的评论,URL中score=3。

说明:该网址中有“fetchJSON”的字样,因而其请求的不是html的网页内容,而是JSON数据文件(JSON是存放数据的一种文件格式)。

r-110-2

第五步:切换到差评

r-110-3

第六步:点击“检查元素”工具栏以“productPageComments...”开头的条目(这一步不同购物网站不一样,需要尝试、摸索、寻找)。右侧的Request URL就是商品评价的网络地址信息。可以看到,对于差评的评论,URL中score=1。

r-110-4

2.2 导入所需的模块

#-*- coding:utf-8 -*-
from urllib.request import Request,urlopen
import pandas as pd
from bs4 import BeautifulSoup
import importlib,sys
importlib.reload(sys)
import json
import jieba
from wordcloud import WordCloud
import numpy as np
from PIL import Image

2.3 获取评价的内容

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.55'
}

# 负面评价
comment_neg=[]
for i in range(0,21):
    url_neg_half1='https://club.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98&productId=100016799352&score=1&sortType=5&page='
    url_neg_half2='&pageSize=10&isShadowSku=0&fold=1'
    url_neg=url_neg_half1+str(i)+url_neg_half2

    req = Request(url_neg, headers=header)
    html = urlopen(req).read().decode('gbk')
    soup = BeautifulSoup(html, 'lxml')
    comment_str = soup.get_text()

    comment_dict = json.loads(comment_str.lstrip('fetchJSON_comment98(').rstrip(');'))
    comments = comment_dict["comments"]

    for comment in comments:
        content = comment['content'].replace('\n', '').replace('\r', '')
        comment_neg.append(content)

# 正面评价
comment_pos=[]
for i in range(0,21):
    url_pos_half1='https://club.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98&productId=100016799352&score=3&sortType=5&page='
    url_pos_half2='&pageSize=10&isShadowSku=0&fold=1'
    url_pos=url_pos_half1+str(i)+url_pos_half2

    req = Request(url_pos, headers=header)
    html = urlopen(req).read().decode('gbk')
    soup = BeautifulSoup(html, 'lxml')
    comment_str = soup.get_text()

    comment_dict = json.loads(comment_str.lstrip('fetchJSON_comment98(').rstrip(');'))
    comments = comment_dict["comments"]

    for comment in comments:
        content = comment['content'].replace('\n', '').replace('\r', '')
        comment_pos.append(content)

3 绘制词云

3.1 负面评价词云

words_neg = jieba.lcut(' '.join(comment_neg))     #精确分词
txt_neg = ' '.join(words_neg)    #空格拼接

stopwords = [line.strip() for line in open('百度停词表.txt', 'r', encoding='utf-8').readlines()]
outwords_neg = ''
for word in txt_neg:
    if word not in stopwords:
        if word != '\t' and '\n':
            outwords_neg = outwords_neg+' '+word

shape = np.array(Image.open("panda.png"))
wordcloud = WordCloud(
    font_path = "msyh.ttc",
    background_color="white",
    width = 800,
    height = 600,
    max_words = 200,
    max_font_size = 80,
    mask = shape,
    contour_width = 3,
    contour_color = 'steelblue'
).generate(outwords_neg)
wordcloud.to_file('词云-负面评价.png')

pyt-169

3.2 正面评价词云

words_pos= jieba.lcut(' '.join(comment_pos))     #精确分词
txt_pos = ' '.join(words_neg)    #空格拼接

stopwords = [line.strip() for line in open('百度停词表.txt', 'r', encoding='utf-8').readlines()]
outwords_pos = ''
for word in txt_pos:
    if word not in stopwords:
        if word != '\t' and '\n':
            outwords_pos = outwords_pos+' '+word

shape = np.array(Image.open("panda.png"))
wordcloud = WordCloud(
    font_path = "msyh.ttc",
    background_color="white",
    width = 800,
    height = 600,
    max_words = 200,
    max_font_size = 80,
    mask = shape,
    contour_width = 3,
    contour_color = 'steelblue'
).generate(outwords_pos)
wordcloud.to_file('词云-正面评价.png')

pyt-170



获取案例数据和源代码,请关注微信公众号并回复:Python_dt33


Comments

Make a comment