python 은 경 동 지정 상품 평론 을 기어 올 라 감정 분석 을 한다.

항목 주소
https://github.com/DA1YAYUAN/JD-comments-sentiment-analysis
경 동상 점 에서 지 정 된 상품 아래 의 사용자 평론 을 올 라 가 데 이 터 를 예 처리 한 후 SnowNLP 의 sentiment 모듈 을 바탕 으로 텍스트 에 대한 감정 분석 을 한다.
운행 환경
  • Mac OS X
  • Python3.7 requirements.txt
  • Pycharm
  • 운행 방법
    데이터 추출(jd.comment.py)
  • jd 시작comment.py,jd 수정 제안comment.py 에서 변수 user-agent 는 자신의 브 라 우 저 사용자 에이전트
  • 경 동 상품 의 전체 URL 입력
  • 경 동 평론 사 구름 을 받 아 jd 에 보관ciyun.jpg(단어 구름 윤곽 모양 은 jdicon.jpg 에 저장)
  • 경 동 평론 데 이 터 를 얻어 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'] + '
    ') # 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('
    ').split(',') print(line_list) writer_csv.writerow(line_list) if __name__ == '__main__': # batch_spider_comment() # txt_change_to_csv() # create_word_cloud()
    모형 훈련(train.py)
  • 양음 어 료 집 online 준비shopping_10_cats.csv,각각 negative.txt 와 positive.txt
  • 를 저장 합 니 다.
  • train.py 를 시작 하고 새 파일 sentiment.marshal 을 시작 하여 훈련 후의 모델
  • 에 저장 합 니 다.
  • 외부 라 이브 러 리 에 있 는 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)
  • sentiment.analysis.py 시작
  • 시작 대 jdcomment.csv 에서 댓 글 을 달 아 데이터 처 리 를 하고 처리 후 파일 을 processed 에 저장 합 니 다.comment_data.csv
  • sentiment 모듈 은 sentiment.marshal.3 에 따라 댓 글 을 감정 적 으로 평가 하고 평가 결 과 는 result.csv
  • 에 저장 합 니 다.
  • 평가 결과 시각 화,파일 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='
    ', 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('
    ', '') } 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 이 경 동 평론 을 올 라 가 감정 분석 을 하 는 자 료 는 우리 의 다른 관련 글 을 주목 하 세 요!

    좋은 웹페이지 즐겨찾기