美文网首页
Python分析QQ群聊记录

Python分析QQ群聊记录

作者: 远方_流浪 | 来源:发表于2018-06-25 10:23 被阅读0次

    说明:本人使用版本,python3.6,编辑器 pycharm 1.8.0


    功能实现:从QQ群导出聊天记录(txt格式),放在程序文件夹中,双击运行程序,即可得到分析结果,包括群活跃成员(Top100),群聊词频统计(Top300)

    <本次分析素材为 当前国内最大的M语言学习群(M与DAX的恩怨纠葛)聊天记录>

    效果图一 :


    活跃度分析.png

    效果图二 :


    聊天词频分析.png

    引用库:

    • os 用于查找当前文件夹内的文件
    • re 聊天记录提取
    • jieba 中文分词工具
    • pyecharts 用于绘制文字云(WordCloud)

    不多说,直接上干货:

    源码:

    # !usr/bin/env python
    # -*-coding:utf-8 -*-
    import os
    import re
    import jieba
    from pyecharts import WordCloud
    
    
    def file_name():
        name = []
        for root, dirs, files in os.walk(os.getcwd()):
            for file in files:
                this_file = os.path.splitext(file)
                if this_file[1].lower() == '.txt':
                    name.append(this_file[0])
            return name
    
    
    def add_dict(dic, words):
        for word in words:
            if len(word.strip()):
                if word in dic:
                    dic[word] += 1
                else:
                    dic[word] = 1
    
    
    def remove_point(dic):
        apl = list(r'\/|{}[]@#$^&*~`;:"<>?,,。、?“”')
        chara = list(r'的了吗吧的么呢啊哪')
        remove_key = list(chr(i) for i in range(0, 128)) + apl + chara
        for each in remove_key:
            try:
                dic.pop(each)
            except:
                pass
    
    
    def dict_sort(dic):
        d = list(zip(dic.keys(), dic.values()))
        dd = sorted(d, key=lambda x: x[1], reverse=True)
        return list(zip(*dd))
    
    
    def wordCloud(title, key, value):
        wordcloud = WordCloud(width=1200, height=750)
        wordcloud.add('', key, value, word_size_range=[15, 120], rotate_step=5)
        # 'circle', 'cardioid', 'diamond', 'triangle-forward', 'triangle', 'pentagon', 'star'
        wordcloud.render(title + '.html')
    
    
    def main(name):
        with open('%s.txt' % name, 'r', encoding='utf-8') as f:
            file = f.read()
        reg = re.compile(r'(\d{4}-\d\d-\d\d).(\d{1,2}:\d\d:\d\d).(.*?)(【\w*?】)?(.*?)[(<].*\D([^`]*?)' + '\n\n')
        res = reg.findall(file)
        print(len(res))
        ttl = {}
        member = {}
        count = 0
        for each in res:
            count += 1
            print('当前进度:%s/%s' %(count, len(res)), end='\r')
            words = list(jieba.cut(each[5], cut_all = True))
            add_dict(ttl, words)
            add_dict(member, {each[2] + each[4]})
        remove_point(ttl)
        member.pop('系统消息')
        member_key, member_value = dict_sort(member)
        ttl_key, ttl_value = dict_sort(ttl)
        wordCloud(name + '_活跃度文字云分析', member_key[:100], member_value[:100])
        wordCloud(name + '_群聊文字云分析', ttl_key[:300], ttl_value[:300])
    
    
    if __name__ == '__main__':
        files = file_name()
        for file in files:
            print('\n当前文件:', file, '\n提取聊天信息数量:', end='')
            main(file)
        input('已完成,按回车键结束……')
    
    

    代码解释:

    1. 前两行,定义解析器和编码方式
    2. import 引入我们需要使用的库
    3. file_name 获取当前文件夹下的聊天记录,返回对应路径
    4. add_dict 使用字典统计词频
    5. remove_point 移除分词结果无用词汇及标点符号(对于不想体现的词汇,均可以在此添加)
    6. dict_sort 按照词频对字典排序
    7. wordCloud 使用pyecharts的文字云工具绘制文字云
    8. main 主函数,控制每一步的进行

    注:

    由QQ直接导出的私聊聊天记录与群聊聊天记录格式略有区别,请勿直接使用此代码分析私聊,关于私聊,请查看另外一篇 https://www.jianshu.com/p/fd7b6c05de7f

    相关文章

      网友评论

          本文标题:Python分析QQ群聊记录

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