美文网首页
用 Python 对 QQ 群消息分析生成词云图

用 Python 对 QQ 群消息分析生成词云图

作者: ajycc20 | 来源:发表于2018-10-02 12:51 被阅读0次

  • 之前看同学在群里发各人的消息云图,然后很好奇就问了下怎么实现的自己也写了一遍 2333

import re
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from scipy.misc import imread

  • 这里是使用的包,用了 jieba 分词和 wordcloud 云图,matplotlib 用来绘图,imread 用来读取生成的云图样式

def seg_sentence(filename):
    message_regex = "(201\d-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) (.*)\n(.*)(?=\n\n)"
    message_complile = re.compile(message_regex)
    with open(filename, encoding='utf-8') as f:
        message_data = message_complile.findall(f.read())
        words = ''
        for rows in message_data:
            if (rows[2] == str):
                seg_list = jieba.cut(rows[3], cut_all=False)
                seg_list = ' '.join(seg_list)
                if len(seg_list) > 1:
                    if seg_list != '\t':
                        words += seg_list
                        words += ' '
        return words

  • 这里使用正则表达式用来匹配 QQ 群导出的 txt 格式消息记录,然后调用 jieba 分词对个人消息进行划分,因为文本格式的消息记录 发的表情和图片都会变成 "[表情]"、"[图片]",一开始我是准备直接用 if 干掉的,后来把这两条添加到了 stopwords 里

def draw_wordcloud(filename):
 
    words = seg_sentence(filename)
 
    font = 'C:\Windows\Fonts\simhei.ttf'
    color_mask = imread('test.jpg')
 
    cloud = WordCloud(font_path=font,
                      background_color='white',
                      mask=color_mask,
                      max_words=400,
                      prefer_horizontal=0.9,
                      stopwords=stopwordslist('stopwords.txt'),
                      # stopwords=None,
                      max_font_size=200)
    word_cloud = cloud.generate(words)
 
    # word_cloud.to_file("cloud.png")
    return word_cloud

  • 绘图的一些格式,这里的 test.jpg 就是我用电脑绘图画了一个云图,用以生成自己想要的云图格式,因为本地绘图产生的图片像素比较低,后来用 ps 把像素提高到 300dpi,这样生成的图片清晰度也高了很多

  • stopwords 用的本地 stopwords,随便下一个就好

def stopwordslist(filepath):
    stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]
    return stopwords

  • 最后就是读取导出的 txt 格式消息记录然后 plt 绘图即可

plt.imshow(word_cloud)
plt.title(u'name', fontproperties='SimHei', fontsize='large')
plt.axis("off")
plt.show()

相关文章

网友评论

      本文标题:用 Python 对 QQ 群消息分析生成词云图

      本文链接:https://www.haomeiwen.com/subject/dsaooftx.html