Python分析QQ私聊记录
2018-06-25 本文已影响0人
远方_流浪
说明:本人使用版本,python3.6,编辑器 pycharm 1.8.0
功能实现:从QQ导出聊天记录(txt格式),放在程序文件夹中,双击运行程序,即可得到词频统计(Top300)
效果图:
私聊效果图.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=1000, height=700)
wordcloud.add('', key, value, word_size_range=[17, 100], rotate_step=20, shape='circle')
# '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).(.*)\D([^`]*?)' + '\n\n')
res = reg.findall(file)
print(len(res))
ttl = {}
count = 0
for each in res:
count += 1
print('当前进度:%s/%s' %(count, len(res)), end='\r')
words = list(jieba.cut(each[3], cut_all=True))
add_dict(ttl, words)
remove_point(ttl)
ttl_key, ttl_value = dict_sort(ttl)
wordCloud(name, ttl_key[:300], ttl_value[:300])
if __name__ == '__main__':
files = file_name()
for file in files:
print('当前文件:', file, '\n提取聊天信息数量:', end='')
main(file)
input('已完成,按回车键结束……')
代码解释:
- 前两行,定义解析器和编码方式
- import 引入我们需要使用的库
- file_name 获取当前文件夹下的聊天记录,返回对应路径
- add_dict 使用字典统计词频
- remove_point 移除分词结果无用词汇及标点符号(对于不想体现的词汇,均可以在此添加)
- dict_sort 按照词频对字典排序
- wordCloud 使用pyecharts的文字云工具绘制文字云
- main 主函数,控制每一步的进行
注:
由QQ直接导出的群聊聊天记录与私聊聊天记录格式略有区别,请勿直接使用此代码分析,关于群聊,请查看另外一篇 https://www.jianshu.com/p/50acede72d52