python 은 경 동 지정 상품 평론 을 기어 올 라 감정 분석 을 한다.
https://github.com/DA1YAYUAN/JD-comments-sentiment-analysis
경 동상 점 에서 지 정 된 상품 아래 의 사용자 평론 을 올 라 가 데 이 터 를 예 처리 한 후 SnowNLP 의 sentiment 모듈 을 바탕 으로 텍스트 에 대한 감정 분석 을 한다.
운행 환경
데이터 추출(jd.comment.py)
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)
# -*-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)
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 이 경 동 평론 을 올 라 가 감정 분석 을 하 는 자 료 는 우리 의 다른 관련 글 을 주목 하 세 요!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
로마 숫자를 정수로 또는 그 반대로 변환그 중 하나는 로마 숫자를 정수로 변환하는 함수를 만드는 것이었고 두 번째는 그 반대를 수행하는 함수를 만드는 것이었습니다. 문자만 포함합니다'I', 'V', 'X', 'L', 'C', 'D', 'M' ; 문자열이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.