本文将从多个方面对Python网易云评论进行详细阐述,关注用户行为、文本情感分析、词云展示等。
一、用户行为分析
首先探讨网易云评论区的一些用户行为特征,可以通过获取评论的点赞数和回复数等数据进行分析。
import requests import re def get_comments_data(music_id): # 通过接口获取音乐ID对应的评论信息 url = 'https://music.163.com/api/v1/resource/comments/R_SO_4_{}?limit=100&offset=0'.format(music_id) user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' headers = {'User-Agent': user_agent} response = requests.get(url, headers=headers) response_data = response.json() # 获取评论内容与点赞数、回复数等信息 data_list = [] for comment in response_data['comments']: data = {} data['comment'] = comment['content'] data['likedCount'] = comment['likedCount'] data['replyCount'] = comment['replyCount'] data_list.append(data) return data_list music_id = '142604' # 此处以周杰伦的歌曲《稻香》为例 comments_data = get_comments_data(music_id)
通过获取到的数据,可以进行用户行为分析。比如可以获取评论区中点赞数TOP10的评论内容。
# 获取点赞数TOP10的评论内容 top_comments = sorted(comments_data, key=lambda x:x['likedCount'], reverse=True)[:10] for comment in top_comments: print(comment['comment'])
二、文本情感分析
接下来可以对评论内容进行情感分析,使用情感分析的方案中,我们使用了TextBlob这个库,该库是一个“纯Python的库,它可以用来进行各种自然语言处理任务,如名词短语提取、单词词形还原、情感分析等”。
from textblob import TextBlob # 对评论内容进行情感分析 for comment in comments_data: blob = TextBlob(comment['comment']) sentiment = blob.sentiment.polarity comment['sentiment'] = sentiment
对情感分析结果进行可视化展示,可以便于更好地观察评论区的整体情感倾向。
import matplotlib.pyplot as plt # 统计情感极性分布 sentiment_list = [comment['sentiment'] for comment in comments_data] positive_num = len([x for x in sentiment_list if x > 0]) negative_num = len([x for x in sentiment_list if x < 0]) neutral_num = len([x for x in sentiment_list if x == 0]) labels = ['Positive', 'Negative', 'Neutral'] sizes = [positive_num, negative_num, neutral_num] colors = ['yellowgreen', 'lightcoral', 'gold'] plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90) plt.axis('equal') plt.show()
三、词云展示
最后可以通过词云的形式,将评论区中出现频率较高的关键词以及其出现的频率展示出来。
from wordcloud import WordCloud import jieba # 中文分词 text = '' for comment in comments_data: text += ' '.join(jieba.cut(comment['comment'], cut_all=False)) # 生成词云 wordcloud = WordCloud(width=800, height=400, margin=2, max_font_size=40, max_words=100, background_color='white').generate(text) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.show()
四、小结
本文通过Python对网易云评论进行了多个方面的分析,展示了在获取音乐ID对应评论信息后,如何对用户行为、文本情感、关键词等进行分析,有助于更好地了解网易云音乐评论区的特征和用户偏好。