时间:2022-12-24 13:50:55 | 栏目:Python代码 | 点击:次
吾的这篇文章,有 1022 次评论,一条条看,吾看不过来,于是想到 Python 词云,提取关键词,倒也是一桩趣事。
评论情况: {'android': 545 次, 'ios': 110 次, 'pc': 44 次, 'uniapp': 1 次}
一个小细节:给我评论的设备中,安卓苹果比是 5:1。
Building prefix dict from the default dictionary ... Loading model cost 0.361 seconds. Prefix dict has been built successfully.
def get_comments(articleId): # 确定评论的页数 main_res = get_commentId(articleId,1) pageCount = json.loads(main_res)['data']['pageCount'] comment_list,comment_list2 = [],[] source_analy = {} for p in range(1,pageCount+1): res = get_commentId(articleId, p) try: commentIds = json.loads(res)['data']['list'] for i in commentIds: commentId = i['info']['commentId'] userName = i['info']['userName'] nickName = i['info']['nickName'] ## 获取用户名 source_dvs = i['info']['commentFromTypeResult']['key'] # 操作设备 content = i['info']['content'] comment_list.append([commentId, userName, nickName, source_dvs, content]) comment_list2.append("%s 丨 %s"%(userName, nickName)) if source_dvs not in source_analy.keys(): source_analy[source_dvs] = 1 else: source_analy[source_dvs] = source_analy[source_dvs] + 1 # print(source_analy) except: print('本页失败!') print('评论数:' + str(len(comment_list))) return source_analy, comment_list, comment_list2
西红柿采用的是 结巴 分词, 和 wordcloud。
# -*- coding:utf8 -*- import jieba import wordcloud
代码实现:
seg_list = jieba.cut(comments, cut_all=False) # 精确模式 word = ' '.join(seg_list)
背景图 西红柿采用的是 心形图片
pic = mpimg.imread('/Users/pray/Downloads/aixin.jpeg')
完整代码::
def word_cloud(articleId): source_analy, comment_list, comment_list2 = get_comments(articleId) print("评论情况:", source_analy) comments = '' for one in comment_list: comment = one[4] if 'face' not in comment: comments = comments + comment seg_list = jieba.cut(comments, cut_all=False) # 精确模式 word = ' '.join(seg_list) pic = mpimg.imread('/Users/pray/Downloads/aixin.jpeg') wc = wordcloud.WordCloud(mask=pic, font_path='/Library/Fonts/Songti.ttc', width=1000, height=500, background_color='white').generate(word)
西红柿发现文字模糊、图像曲线边缘不清晰的问题。
于是,指定分辨率,高清整起来。
# 保存 plt.savefig('xin300.png', dpi=300) #指定分辨率保存