最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python 爬取京東指定商品評(píng)論并進(jìn)行情感分析

 更新時(shí)間:2021年05月27日 17:16:13   作者:DA1YAYUAN  
本文主要講述了利用Python網(wǎng)絡(luò)爬蟲(chóng)對(duì)指定京東商城中指定商品下的用戶評(píng)論進(jìn)行爬取,對(duì)數(shù)據(jù)預(yù)處理操作后進(jìn)行文本情感分析,感興趣的朋友可以了解下

項(xiàng)目地址

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

爬取京東商城中指定商品下的用戶評(píng)論,對(duì)數(shù)據(jù)預(yù)處理后基于SnowNLP的sentiment模塊對(duì)文本進(jìn)行情感分析。

運(yùn)行環(huán)境

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

運(yùn)行方法

數(shù)據(jù)爬?。╦d.comment.py)

  1. 啟動(dòng)jd_comment.py,建議修改jd_comment.py中變量user-agent為自己瀏覽器用戶代理
  2. 輸入京東商品完整URL
  3. 得到京東評(píng)論詞云,存放于jd_ciyun.jpg(詞云輪廓形狀存放于jdicon.jpg)
  4. 得到京東評(píng)論數(shù)據(jù),存放于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'
# 評(píng)論數(shù)據(jù)保存文件
COMMENT_FILE_PATH = 'jd_comment.txt'
# 詞云字體
WC_FONT_PATH = '/Library/Fonts/Songti.ttc'


def spider_comment(page=0, key=0):
    """
    爬取京東指定頁(yè)的評(píng)價(jià)數(shù)據(jù)
    :param page: 爬取第幾,默認(rèn)值為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不輸入值,默認(rèn)為《三體》

    try:
        r = requests.get(url, headers=kv)
        r.raise_for_status()
    except:
        print('爬取失敗')
    # 截取json數(shù)據(jù)字符串
    r_json_str = r.text[26:-2]
    # 字符串轉(zhuǎn)json對(duì)象
    r_json_obj = json.loads(r_json_str)
    # 獲取評(píng)價(jià)列表數(shù)據(jù)
    r_json_comments = r_json_obj['comments']
    # 遍歷評(píng)論對(duì)象列表
    for r_json_comment in r_json_comments:
        # 以追加模式換行寫(xiě)入每條評(píng)價(jià)
        with open(COMMENT_FILE_PATH, 'a+') as file:
            file.write(r_json_comment['content'] + '\n')
        # 打印評(píng)論對(duì)象中的評(píng)論內(nèi)容
        print(r_json_comment['content'])


def batch_spider_comment():
    """
        批量爬取某東評(píng)價(jià)
        """
    # 寫(xiě)入數(shù)據(jù)前先清空之前的數(shù)據(jù)
    if os.path.exists(COMMENT_FILE_PATH):
        os.remove(COMMENT_FILE_PATH)
    key = input("Please enter the address:")
    key = re.sub("\D","",key)
    #通過(guò)range來(lái)設(shè)定爬取的頁(yè)面數(shù)
    for i in range(10):
        spider_comment(i,key)
        # 模擬用戶瀏覽,設(shè)置一個(gè)爬蟲(chóng)間隔,防止ip被封
        time.sleep(random.random() * 5)


def cut_word():
    """
    對(duì)數(shù)據(jù)分詞
    :return: 分詞后的數(shù)據(jù)
    """
    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:
    """
    # 設(shè)置詞云形狀圖片
    wc_mask = np.array(Image.open(WC_MASK_IMG))
    # 設(shè)置詞云的一些配置,如:字體,背景色,詞云形狀,大小
    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())
    # 在只設(shè)置mask的情況下,你將會(huì)得到一個(gè)擁有圖片形狀的詞云
    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__':
    # 爬取數(shù)據(jù)
    batch_spider_comment()

    #轉(zhuǎn)換數(shù)據(jù)
    txt_change_to_csv()

    # 生成詞云
    create_word_cloud()

模型訓(xùn)練(train.py)

  1. 準(zhǔn)備正負(fù)語(yǔ)料集online_shopping_10_cats.csv,分別存入negative.txt和positive.txt
  2. 啟動(dòng)train.py,新建文件sentiment.marshal,存入訓(xùn)練后的模型
  3. 找到外部庫(kù)中snownlp中sentiment模塊,將訓(xùn)練得到的sentiment.marshal.3文件覆蓋sentiment模塊中自帶的sentiment.marshal.3
# -*-coding:utf-8-*-

def train():
    from snownlp import sentiment
    print("開(kāi)始訓(xùn)練數(shù)據(jù)集...")
    sentiment.train('negative.txt', 'positive.txt')#自己準(zhǔn)備數(shù)據(jù)集
    sentiment.save('sentiment.marshal')#保存訓(xùn)練模型
    #python2保存的是sentiment.marshal;python3保存的是sentiment.marshal.3
    "訓(xùn)練完成后,將訓(xùn)練完的模型,替換sentiment中的模型"

def main():
    train()  # 訓(xùn)練正負(fù)向商品評(píng)論數(shù)據(jù)集
    print("數(shù)據(jù)集訓(xùn)練完成!")

if __name__ == '__main__':
    main()

情感分析(sentiment.analysis.py)

  1. 啟動(dòng)sentiment.analysis.py
  2. 開(kāi)始對(duì)jd_comment.csv中評(píng)論進(jìn)行數(shù)據(jù)處理,處理后文件存入processed_comment_data.csv
  3. sentiment模塊根據(jù)sentiment.marshal.3對(duì)評(píng)論進(jìn)行情感評(píng)分,評(píng)分結(jié)果存入result.csv
  4. 評(píng)分結(jié)果可視化,生成文件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():
    '''讀取商品評(píng)論數(shù)據(jù)文件'''
    comment_data = pd.read_csv('jd_comment.csv', encoding='utf-8',
                               sep='\n', index_col=None)
    #返回評(píng)論作為參數(shù)
    return comment_data


def clean_data(data):
    '''數(shù)據(jù)清洗'''
    df = data.dropna()  # 消除缺失數(shù)據(jù) NaN為缺失數(shù)據(jù)
    df = pd.DataFrame(df.iloc[:, 0].unique())  # 數(shù)據(jù)去重
    return df
    # print('數(shù)據(jù)清洗后:', len(df))


def clean_repeat_word(raw_str, reverse=False):
    '''去除評(píng)論中的重復(fù)使用的詞匯'''
    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):
    '''清洗完畢的數(shù)據(jù),并保存'''
    df = clean_data(read_csv())#數(shù)據(jù)清洗
    ser1 = df.iloc[:, 0].apply(clean_repeat_word)#去除重復(fù)詞匯
    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():
    '''訓(xùn)練正向和負(fù)向情感數(shù)據(jù)集,并保存訓(xùn)練模型'''
    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):
    '''商品評(píng)論-情感分析-測(cè)試'''
    with open(f'{filename}.csv', 'r', encoding='utf-8') as fr:
        for line in fr.readlines():
            s = snownlp.SnowNLP(line)
            #調(diào)用snownlp中情感評(píng)分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 = {
                '情感分析結(jié)果': s.sentiments,
                '評(píng)價(jià)傾向': res,
                '商品評(píng)論': 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():
    '''分析結(jié)果可視化,以條形圖為測(cè)試樣例'''
    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='喜歡')#(坐標(biāo),評(píng)論長(zhǎng)度,名稱)
    plt.bar([2], [common], label='一般')
    plt.bar([3], [unlikes], label='不喜歡')

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

    plt.legend()#插入圖例
    plt.xlabel('評(píng)價(jià)種類(lèi)')
    plt.ylabel('評(píng)價(jià)數(shù)目')
    plt.title(u'商品評(píng)論情感分析結(jié)果-條形圖', FontProperties=font)
    plt.savefig('fig.png')
    plt.show()
'''
def word_cloud_show():
    #將商品評(píng)論轉(zhuǎn)為高頻詞匯的詞云
    wl = word_cloud_creation('jd_comment.csv')
    wc = word_cloud_settings()
    word_cloud_implementation(wl, wc)
'''

def main():
     processed_data('processed_comment_data')#數(shù)據(jù)清洗
     #train()  # 訓(xùn)練正負(fù)向商品評(píng)論數(shù)據(jù)集

     test('jd_comment', 'result')

     print('數(shù)據(jù)可視化中...')
     data_virtualization()  # 數(shù)據(jù)可視化

     print('python程序運(yùn)行結(jié)束。')

if __name__ == '__main__':
    main()

詞云輪廓圖

商品評(píng)論詞云

情感分析結(jié)果可視化

以上就是python 爬取京東指定商品評(píng)論并進(jìn)行情感分析的詳細(xì)內(nèi)容,更多關(guān)于python 爬取京東評(píng)論并進(jìn)行情感分析的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • python使用paramiko實(shí)現(xiàn)ssh的功能詳解

    python使用paramiko實(shí)現(xiàn)ssh的功能詳解

    這篇文章主要介紹了python使用paramiko實(shí)現(xiàn)ssh的功能詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • Python讀取HTML中的canvas并且以圖片形式存入Word文檔

    Python讀取HTML中的canvas并且以圖片形式存入Word文檔

    這篇文章主要介紹了Python讀取HTML中的canvas并且以圖片形式存入Word文檔,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-08-08
  • pytorch 彩色圖像轉(zhuǎn)灰度圖像實(shí)例

    pytorch 彩色圖像轉(zhuǎn)灰度圖像實(shí)例

    今天小編就為大家分享一篇pytorch 彩色圖像轉(zhuǎn)灰度圖像實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-01-01
  • Python3多線程基礎(chǔ)知識(shí)點(diǎn)

    Python3多線程基礎(chǔ)知識(shí)點(diǎn)

    在本篇內(nèi)容里小編給大家分享了關(guān)于Python3多線程基礎(chǔ)知識(shí)點(diǎn)內(nèi)容,需要的朋友們跟著學(xué)習(xí)參考下。
    2019-02-02
  • python根據(jù)list重命名文件夾里的所有文件實(shí)例

    python根據(jù)list重命名文件夾里的所有文件實(shí)例

    今天小編就為大家分享一篇python根據(jù)list重命名文件夾里的所有文件實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-10-10
  • Appium自動(dòng)化測(cè)試實(shí)現(xiàn)九宮格解鎖

    Appium自動(dòng)化測(cè)試實(shí)現(xiàn)九宮格解鎖

    本文主要介紹了Appium自動(dòng)化測(cè)試實(shí)現(xiàn)九宮格解鎖,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • Python繪制線圖之plt.plot()的介紹以及使用

    Python繪制線圖之plt.plot()的介紹以及使用

    在Python中plt.plot是matplotlib庫(kù)中的一個(gè)函數(shù),用于繪制點(diǎn)和線,并對(duì)其樣式進(jìn)行控制,下面這篇文章主要給大家介紹了關(guān)于Python繪制線圖之plt.plot()的介紹以及使用的相關(guān)資料,需要的朋友可以參考下
    2023-12-12
  • 人工智能-Python實(shí)現(xiàn)嶺回歸

    人工智能-Python實(shí)現(xiàn)嶺回歸

    本文介紹人工智能-Python實(shí)現(xiàn)嶺回歸,?是一種專(zhuān)用于共線性數(shù)據(jù)分析的有偏估計(jì)回歸方法,實(shí)質(zhì)上是一種改良的最小二乘估計(jì)法,通過(guò)放棄最小二乘法的無(wú)偏性,以損失部分信息、降低精度為代價(jià)獲得回歸系數(shù)更為符合實(shí)際、更可靠的回歸方法,對(duì)病態(tài)數(shù)據(jù)的擬合要強(qiáng)于最小二乘法
    2022-01-01
  • Python-基礎(chǔ)-入門(mén) 簡(jiǎn)介

    Python-基礎(chǔ)-入門(mén) 簡(jiǎn)介

    這篇文章主要介紹了Python-基礎(chǔ)-簡(jiǎn)介入門(mén)的相關(guān)資料,需要的朋友可以參考下
    2014-08-08
  • python網(wǎng)絡(luò)編程學(xué)習(xí)筆記(九):數(shù)據(jù)庫(kù)客戶端 DB-API

    python網(wǎng)絡(luò)編程學(xué)習(xí)筆記(九):數(shù)據(jù)庫(kù)客戶端 DB-API

    這篇文章主要介紹了python 數(shù)據(jù)庫(kù)客戶端 DB-API的相關(guān)資料,需要的朋友可以參考下
    2014-06-06

最新評(píng)論

白银市| 曲阳县| 榆社县| 万源市| 白沙| 东宁县| 米易县| 织金县| 乌兰察布市| 南漳县| 夏津县| 浮梁县| 云和县| 长治市| 广宁县| 绍兴县| 句容市| 柯坪县| 合山市| 兴安盟| 丽江市| 沛县| 米脂县| 凌云县| 牙克石市| 青海省| 红安县| 香河县| 凯里市| 河津市| 孟津县| 财经| 南平市| 邯郸县| 广昌县| 比如县| 明水县| 张家界市| 交城县| 平度市| 甘孜县|