├── .gitignore ├── README.md ├── chatlog ├── analysis │ ├── collectivity.py │ ├── content.py │ ├── individual.py │ └── interesting.py ├── base │ ├── constant.py │ ├── read_chatlog.py │ ├── seg_word.py │ └── user_profile.py ├── model │ ├── message.py │ └── user.py ├── run.py └── visualization │ ├── cat.png │ ├── cat2.png │ ├── cat3.png │ ├── charts.py │ ├── msyh.ttc │ └── word_img.py ├── license └── photos ├── PL_wordcloud.png ├── README.md ├── all_wordcloud0.png ├── all_wordcloud1.png ├── all_wordcloud2.png ├── all_wordcloud3.png ├── company_wordcloud.png ├── speak_photo_in_total.png └── user_time_online.png /.gitignore: -------------------------------------------------------------------------------- 1 | *.txt 2 | /TEST/ 3 | .idea/ 4 | /.idea 5 | /.idea/ 6 | .idea -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ChatLog 2 | 3 | 通过QQ导出的QQ群聊天记录进行一定的分析。 4 | 5 | just a toy 6 | 7 | ## 开发日志 8 | 9 | 2020-08-27 完成数据处理部分代码清洗,优化部分代码。 10 | 11 | ## 基本功能 12 | 13 | * QQ群聊天记录的数据清洗 14 | * 构建简单用户画像 15 | * 简单分析与统计 16 | * 部分数据可视化 17 | 18 | ## 安装说明 19 | 20 | python版本:`3.6.x` 21 | 22 | 系统平台:`windows` 23 | 24 | 需要的第三方库:`pymongo,pandas,jieba,seaborn,numpy` 25 | 26 | 以上均可通过`pip install `安装 27 | 28 | 需要的软件:`MongoDB` 29 | 30 | ## 说明 31 | 32 | ### 1.base 33 | 34 | - read_chatlog.py 35 | 36 | 对导出的.txt聊天记录文件进行数据清洗。 37 | 38 | `注意:腾讯导出的聊天记录是UTF-8+bom的 需改成 -bom` 39 | 40 | 清洗后的数据存入mongo数据库中,具体数据如下: 41 | 42 | | 数据项 | 说明 | 43 | | ---- | :----------- | 44 | | time | 消息发送时间 | 45 | | ID | QQ号或邮箱 | 46 | | name | 发送该消息时所使用的马甲 | 47 | | text | 发送消息的内容 | 48 | 49 | 50 | 51 | - user_profile.py 52 | 53 | 通过清洗好的数据构建用户画像,并保存到mongo数据库中。 54 | 55 | 用户基本画像数据如下: 56 | 57 | | 数据项 | 说明 | 58 | | ----------- | ------------------ | 59 | | ID | QQ号或邮箱 | 60 | | name_list | 可统计得到的所有马甲 | 61 | | speak_num | 发言次数 | 62 | | word_num | 发言字数 | 63 | | photos_num | 发送图片数 | 64 | | week_online | 记录着周一到周日每天每小时的活跃数据 | 65 | | ban_time | 被禁言时间(有待改进) | 66 | 67 | 68 | 69 | 70 | 71 | - seg_word.py 72 | 73 | 通过[jieba](https://github.com/fxsjy/jieba)分词工具将文本进行分析,统计词频并去停用词后保存。 74 | 75 | - chinese_stopword.txt 76 | 77 | 停用词典。 78 | 79 | 80 | 81 | ### 2.analysis 82 | 83 | - individual.py 84 | 85 | 个人数据统计,分析发言次数最多,发送字数最多,发送图片最多,被禁言时长最长的用户。 86 | 87 | - collecticity.py 88 | 89 | 总体数据分析,分析群活跃时间。 90 | 91 | - interesting.py 92 | 93 | 因吹斯听的分析。 94 | 95 | - 马甲最长的聚聚 96 | - 改名次数最多的聚聚 97 | - 群内队形(+1)次数最多的内容,即使局部打断也可统计。 98 | 99 | - content.py 100 | 101 | 开发中 102 | 103 | 104 | 105 | ### 3.visualization 106 | 107 | - charts.py 108 | 109 | 将部分数据可视化。如下: 110 | 111 | 用户活跃时间heatmap,横轴为一天0-24时,纵轴为周一到周日。颜色越深的方块活跃程度越高。 112 | 113 | ![heatmap](https://github.com/DingHanyang/chatLog/blob/master/photos/user_time_online.png?raw=true) 114 | 115 | 用户发言数TOP10及发表图片所占比例。 116 | 117 | ![photos](https://github.com/DingHanyang/chatLog/blob/master/photos/speak_photo_in_total.png?raw=true) 118 | 119 | 120 | 121 | - word_img.py 122 | 123 | 构建词云。分析群内常用词及部分话题,如下: 124 | 125 | 针对所有信息进行词云 126 | 127 | - 构建词长度大于0: 128 | 129 | ![Word1](https://github.com/DingHanyang/chatLog/blob/master/photos/all_wordcloud0.png?raw=true) 130 | 131 | - 词长度大于1: 132 | 133 | ![word2](https://github.com/DingHanyang/chatLog/blob/master/photos/all_wordcloud1.png?raw=true) 134 | 135 | - 词长度大于3: 136 | 137 | ![all_wordcloud3.png](https://github.com/DingHanyang/chatLog/blob/master/photos/all_wordcloud3.png?raw=true) 138 | 139 | 针对群聊天记录构建的词云: 140 | 141 | 因为测试数据为技(zhuang)术(bi)群,所以本项不具有通用性。具体实现在[此处](https://github.com/DingHanyang/chatLog/blob/master/visualization/Wordcloud.py) 142 | 143 | - 针对经常谈论的公司: 144 | 145 | ![word4](https://github.com/DingHanyang/chatLog/blob/master/photos/company_wordcloud.png?raw=true) 146 | 147 | - 针对谈论的编程语言: 148 | 149 | ![word5](https://github.com/DingHanyang/chatLog/blob/master/photos/PL_wordcloud.png?raw=true) 150 | 151 | 152 | 153 | 154 | ## 运行 155 | 156 | 0.clone本项目到本地。 157 | 158 | 1.手动从QQ消息管理器中导出消息,注意改为UTF-8-BOM。并将其命名为chatlog.txt放置于run.py同级目录下。 159 | 160 | 2.开启mongodb服务,运行run.py 161 | 162 | 3.易于修改的参数有: 163 | 164 | - 群等级标签:[DataClean.py](https://github.com/DingHanyang/chatLog/blob/master/base/DataClean.py) line83:根据不同群等级标签修改。不改无妨,影响用户名称显示 165 | - 词云样式及背景图片:[Wordcloud](https://github.com/DingHanyang/chatLog/blob/master/visualization/Wordcloud.py) 166 | - 词云屏蔽词:[Wordcloud](https://github.com/DingHanyang/chatLog/blob/master/visualization/Wordcloud.py) line45:此处已经屏蔽‘图片’,‘表情’,‘说’ 167 | 168 | 169 | 170 | ## 最后 171 | 172 | 填坑中,希望收到改进意见。 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | -------------------------------------------------------------------------------- /chatlog/analysis/collectivity.py: -------------------------------------------------------------------------------- 1 | """ 2 | 总体数据统计分析 3 | @author:DingHanyang 4 | """ 5 | import numpy 6 | from pymongo import MongoClient 7 | 8 | 9 | class Collectivity(object): 10 | def __init__(self): 11 | self.client = MongoClient() # 默认连接 localhost 27017 12 | self.db = self.client.chatlog 13 | self.post = self.db.vczh 14 | 15 | def get_all_speak_info(self): 16 | """ 17 | 群总体在线时间分布 18 | :return: 19 | """ 20 | post = self.db.profile 21 | week_online = numpy.zeros((7, 24), dtype=numpy.int) 22 | for doc in post.find({}, {'week_online': 1}): 23 | week_online += numpy.array(doc['week_online']) 24 | 25 | return week_online.tolist() 26 | 27 | def close(self): 28 | self.client.close() 29 | -------------------------------------------------------------------------------- /chatlog/analysis/content.py: -------------------------------------------------------------------------------- 1 | """ 2 | 聊天内容分析 3 | @author:DingHanyang 4 | """ 5 | from pymongo import MongoClient 6 | 7 | 8 | class ChatText(object): 9 | def __init__(self): 10 | self.client = MongoClient() # 默认连接 localhost 27017 11 | self.db = self.client.chatlog 12 | self.post = self.db.vczh 13 | 14 | # TODO:一个大坑未填 15 | -------------------------------------------------------------------------------- /chatlog/analysis/individual.py: -------------------------------------------------------------------------------- 1 | """ 2 | 个体数据统计分析 3 | @author:DingHanyang 4 | """ 5 | from pymongo import MongoClient 6 | 7 | 8 | class Individual(object): 9 | def __init__(self): 10 | self.client = MongoClient() # 默认连接 localhost 27017 11 | self.db = self.client.chatlog 12 | self.post = self.db.profile 13 | 14 | def most_speak(self, send_class='speak_num'): 15 | """ 16 | 发言次数最多、发送字数最多、发送图片最多的用户排行 17 | :param send_class:选择 speak_num,word_num,photo_num 18 | :return:[(ID1,name1,num),(ID1,name2,num),...] 19 | """ 20 | top_list = [] 21 | for doc in self.post.find({}, {send_class: 1, 'name_list': 1, 'ID': 1}): 22 | top_list.append((doc['ID'], doc['name_list'][len(doc['name_list']) - 1], doc[send_class])) 23 | 24 | return sorted(top_list, key=lambda x: x[2], reverse=True) 25 | 26 | def longest_ban(self): 27 | """ 28 | 被禁言时间最长的人榜单 29 | :return:[(name1,time),(name2,time),...] 30 | """ 31 | self.post = self.db.profile 32 | top_list = [] 33 | for doc in self.post.find({}, {'ID': 1, 'ban_time': 1, 'name_list': 1}): 34 | top_list.append((doc['ID'], doc['name_list'][len(doc['name_list']) - 1], doc['ban_time'])) 35 | 36 | return sorted(top_list, key=lambda x: x[2], reverse=True) 37 | 38 | def close(self): 39 | self.client.close() 40 | -------------------------------------------------------------------------------- /chatlog/analysis/interesting.py: -------------------------------------------------------------------------------- 1 | """ 2 | 因吹斯听 分析及统计 3 | @author:DingHanyang 4 | """ 5 | from pymongo import MongoClient 6 | 7 | 8 | class Interesting(object): 9 | def __init__(self): 10 | self.client = MongoClient() # 默认连接 localhost 27017 11 | self.db = self.client.chatlog 12 | self.post = self.db.vczh 13 | 14 | def longest_name(self): 15 | """ 16 | 取出所有用户的name,并排序。 17 | ..note::由于聊天记录时间跨度大,有的聚聚改名频繁,而有些名字由于QQ保存的原因保存成了QQ号而丢失 18 | :return:top_list[('name',len(name)),(...,...),...] 按长度从大到小排序 19 | """ 20 | res_list = [] 21 | for doc in self.post.find({}, {'name': 1}): 22 | res_list.append(doc['name']) 23 | res_list = {}.fromkeys(res_list).keys() 24 | 25 | top_list = [] 26 | for li in res_list: 27 | top_list.append((li, len(li))) 28 | 29 | return sorted(top_list, key=lambda x: x[1], reverse=True) 30 | 31 | def longest_formation(self): 32 | """ 33 | 所有记录中,跟队形最长的聊天记录。 34 | :return:top_list[('text',len(text)),(...,...),...] 按长度从大到小排序 35 | """ 36 | res_list = [] 37 | for doc in self.post.find({}, {'text': 1}): 38 | res_list.append(doc['text']) 39 | 40 | top_list = [] 41 | # text 数据存储形式 [[sentences1],[sentences2],...] 队形大多只有一句 所以只考虑text长度为1的 42 | i = 0 43 | while i < len(res_list) - 1: 44 | if res_list[i][0] == '[图片]': 45 | i += 1 46 | elif res_list[i][0] == res_list[i + 1][0]: 47 | pos = i + 1 48 | while pos < len(res_list) - 1: 49 | if res_list[pos][0] == res_list[pos + 1][0]: 50 | pos += 1 51 | else: 52 | if pos - i + 1 > 2: 53 | top_list.append((res_list[i][0], pos - i + 1)) 54 | i = pos + 1 55 | break 56 | else: 57 | i += 1 58 | 59 | # 例如中间有人插话一句将队形打断的话,整合队形 60 | k = 0 61 | while k < len(top_list) - 1: 62 | if top_list[k][0] == top_list[k + 1][0]: 63 | top_list.append((top_list[k][0], top_list[k][1] + top_list[k + 1][1])) 64 | top_list.pop(k - 1) 65 | top_list.pop(k) 66 | else: 67 | k += 1 68 | return sorted(top_list, key=lambda x: x[1], reverse=True) 69 | 70 | def close(self): 71 | self.client.close() 72 | -------------------------------------------------------------------------------- /chatlog/base/constant.py: -------------------------------------------------------------------------------- 1 | # re 2 | JUDGE_TIME_RE = '^(((20[0-3][0-9]-(0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|(20[0-3][0-9]-(0[2469]|11)-(0[1-9]|[12][' \ 3 | '0-9]|30))) (20|21|22|23|[0-9]|[0-1][0-9]):[0-5][0-9]:[0-5][0-9])' 4 | JUDGE_ID_RE = '[(][1-9]\d{4,}[)]$|[<][A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}[>]$' 5 | -------------------------------------------------------------------------------- /chatlog/base/read_chatlog.py: -------------------------------------------------------------------------------- 1 | import re 2 | from pymongo import MongoClient 3 | 4 | from chatlog.base import constant 5 | 6 | 7 | class ReadChatlog(object): 8 | def __init__(self, file_path, db_name='chatlog', collection_name='vczh'): 9 | self.file_path = file_path 10 | self.client = MongoClient() # 默认连接 localhost 27017 11 | self.db = self.client[db_name] 12 | self.post = self.db[collection_name] 13 | 14 | # 初始化两个常用正则 15 | self.time_pattern = re.compile(constant.JUDGE_TIME_RE) 16 | self.ID_pattern = re.compile(constant.JUDGE_ID_RE) 17 | 18 | def _judge_start_line(self, message): 19 | """ 20 | 判断某行是不是起始行 21 | 条件1:YYYY-MM-DD HH-MM-SS开头(长度大于19) 22 | 条件2::(XXXXXXXXX)或者结尾 23 | :return: False or (time,ID) 24 | """ 25 | if len(message) > 19 and (self.time_pattern.match(message)) and (self.ID_pattern.search(message)): 26 | return self.time_pattern.search(message).group(), self.ID_pattern.search(message).group() 27 | return False 28 | 29 | def work(self): 30 | """ 31 | 腾讯导出的聊天记录是UTF-8+bom的 手动改成-bom 32 | 进行数据清洗,将原始数据划分成块保存进mongodb中 33 | ..note::例子 34 | time:YYYY-MM-DD HH-MM-SS 35 | ID:(XXXXXXXXX)或者 36 | name:username 37 | text:['sentence1','sentence2',...] 38 | """ 39 | print('----------正在进行数据清洗-------------') 40 | 41 | with open(self.file_path, 'r', encoding='utf-8') as chatlog_file: 42 | chatlog_list = [line.strip() for line in chatlog_file if line.strip() != ""] 43 | 44 | now_cursor = 0 # 当前分析位置 45 | last = 0 # 上一个行首位置 46 | flag = 0 47 | first_line_info = self._judge_start_line(str(chatlog_list[now_cursor])) 48 | while now_cursor < len(chatlog_list): 49 | if self._judge_start_line(str(chatlog_list[now_cursor])): 50 | if not flag: 51 | first_line_info = self._judge_start_line(str(chatlog_list[now_cursor])) 52 | last = now_cursor 53 | flag = 1 54 | else: 55 | flag = 0 56 | send_time = first_line_info[0] 57 | send_id = first_line_info[1] 58 | # 如果什么消息都没发直接不插入 59 | if not chatlog_list[last + 1:now_cursor]: 60 | continue 61 | # 发送该消息时用户的马甲 62 | name = chatlog_list[last].replace(send_id, "").replace(send_time, "").lstrip() 63 | 64 | for extra_char in '()<>': 65 | send_id = send_id.replace(extra_char, "") 66 | 67 | # 由于等级标签有极大部分缺失,所以直接去除 68 | # TODO:消息中大频率出现的标签应该就是等级标签,应自检测 69 | for i in ['【实习】', '【能写代码】', '【专属骚头衔】', '【群地位倒数】', '【实习】', '【管理员】']: 70 | if name[:len(i)] == i: 71 | name = name.replace(i, "") 72 | 73 | # 将时间格式统一 74 | for li in '0123456789': 75 | send_time = send_time.replace(' ' + li + ':', ' 0' + li + ':') 76 | 77 | self.post.insert_one({'time': send_time, 'ID': send_id, 'name': name, 78 | 'text': chatlog_list[last + 1:now_cursor]}) 79 | 80 | print('time:', send_time, 'ID:', send_id, 'name:', name) 81 | print(chatlog_list[last + 1:now_cursor]) 82 | print("------------------------------------------------") 83 | continue 84 | now_cursor += 1 85 | self.client.close() 86 | print('----------数据清洗完成-------------') -------------------------------------------------------------------------------- /chatlog/base/seg_word.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | import jieba 3 | from pymongo import MongoClient 4 | 5 | 6 | class SegWord(object): 7 | def __init__(self): 8 | self.client = MongoClient() # 默认连接 localhost 27017 9 | self.db = self.client.chatlog 10 | self.post = self.db.vczh 11 | 12 | def work(self): 13 | stopword_list = [] 14 | fp = open('../base/chinese_stopword.txt', 'r', encoding='utf-8') 15 | for line in fp.readlines(): 16 | stopword_list.append(line.replace('\n', '')) 17 | fp.close() 18 | 19 | word_list = [] 20 | for doc in self.post.find({}, {'text': 1}): 21 | print(len(word_list)) 22 | word_list.extend(jieba.lcut(doc['text'][0])) 23 | word_dict = Counter(word_list) 24 | self.post = self.db.word 25 | for key in word_dict.keys(): 26 | if str(key) in stopword_list: 27 | print(key) 28 | continue 29 | self.post.insert({'word': key, 'item': word_dict[key]}) 30 | self.close() 31 | 32 | def close(self): 33 | self.client.close() 34 | 35 | -------------------------------------------------------------------------------- /chatlog/base/user_profile.py: -------------------------------------------------------------------------------- 1 | """ 2 | 构建用户基本画像 3 | @author:DingHanyang 4 | """ 5 | from datetime import datetime 6 | from pymongo import MongoClient 7 | 8 | 9 | class UserProfile: 10 | def __init__(self, db_name='chatlog', collection_name='vczh'): 11 | print("正在初始化用户画像模块") 12 | self.client = MongoClient() # 默认连接 localhost 27017 13 | self.db = self.client[db_name] 14 | self.post = self.db[collection_name] 15 | 16 | self.res_list = [doc for doc in self.post.find({}, {'_id': 0})] 17 | 18 | def close(self): 19 | self.client.close() 20 | 21 | def _get_user_id_list(self): 22 | """ 23 | 获取记录中所有ID的列表 24 | :return:[id1,id2,id3,...] 25 | """ 26 | user_id_list = [li['ID'] for li in self.res_list] 27 | 28 | user_id_list = list(set(user_id_list)) 29 | print('记录中共有', len(user_id_list), '位聚聚发过言') 30 | 31 | return user_id_list 32 | 33 | def _get_all_name(self, user_id): 34 | """ 35 | 根据ID返回一个用户所有曾用名 36 | :param user_id:用户ID 37 | :return:{'name1','name2',...} 38 | """ 39 | name_list = set() 40 | for li in self.res_list: 41 | if li['ID'] == user_id: 42 | name_list.add(li['name']) 43 | 44 | return list(name_list) 45 | 46 | def _get_speak_infos(self, user_id): 47 | """ 48 | 返回一个用户的发言次数,发言文字数,发言图片数 49 | :param user_id:用户ID 50 | :return:[speak_num,word_num,photo_num] 51 | """ 52 | speak_num = 0 53 | word_num = 0 54 | photo_num = 0 55 | for li in self.res_list: 56 | if li['ID'] == user_id: 57 | speak_num += 1 58 | for sp in li['text']: 59 | word_num += len(sp) 60 | photo_num += sp.count('[图片]') 61 | return speak_num, word_num, photo_num 62 | 63 | def _get_online_time(self, user_id): 64 | """ 65 | 返回一个用户在那个时段发言数最多(0-24小时)(周1-7) 66 | :param user_id:用户ID 67 | :return:[[0,0,0,0],[],[],[],...] [周1-7]包含[0-24小时] 68 | """ 69 | time_list = [] 70 | for li in self.res_list: 71 | if li['ID'] == user_id: 72 | time_list.append(li['time']) 73 | 74 | week_list = [[0 for _ in range(24)] for _ in range(7)] 75 | 76 | for li in time_list: 77 | week_list[int(datetime.strptime(li, "%Y-%m-%d %H:%M:%S").weekday())][int(li[11:13])] += 1 78 | 79 | return week_list 80 | 81 | def work(self): 82 | """ 83 | 分析所有用户基本画像并存入数据库 84 | ..note:: 85 | ID: 86 | name:[name1,name2,...] 87 | speak_num:发言次数 88 | word_num:发言字数 89 | photo_num:发布图片数 90 | week_online:周活跃分布 91 | :return:None 92 | """ 93 | post = self.db.profile 94 | user_id_list = self._get_user_id_list() 95 | for li in user_id_list: 96 | print('正在构建用户', li, '的用户画像') 97 | name_list = self._get_all_name(li) 98 | speak_num, word_num, photo_num = self._get_speak_infos(li) 99 | week_online = self._get_online_time(li) 100 | ban_time = self._ban_time(li) 101 | post.insert_one({'ID': li, 'name_list': name_list, 'speak_num': speak_num, 102 | 'word_num': word_num, 'photo_num': photo_num, 103 | 'week_online': week_online, 'ban_time': ban_time}) 104 | self.close() 105 | 106 | # TODO 管理员若解禁则扣除时间 107 | def _ban_time(self, user_id): 108 | """ 109 | 统计用户累计禁言时间 110 | :return: 111 | """ 112 | 113 | def add_time(add_list): 114 | time = 0 115 | for times in add_list: 116 | for info in [('天', 60 * 24), ('小时', 60), ('分钟', 1)]: 117 | if info[0] in times: 118 | index = times.find(info[0]) 119 | if times[index - 2].isdigit(): 120 | time += int(times[index - 2:index]) * info[1] 121 | else: 122 | time += int(times[index - 1:index]) * info[1] 123 | return time 124 | 125 | name_list = self._get_all_name(user_id) 126 | res_list = [] 127 | for li in self.post.find({'ID': '10000'}, {'text': 1}): 128 | if '被管理员禁言' in li['text'][0]: 129 | res_list.append(li['text'][0].split(' 被管理员禁言')) 130 | 131 | time_list = [] 132 | for li in res_list: 133 | for name in name_list: 134 | if li[0] == name: 135 | time_list.append(li[1]) 136 | 137 | return add_time(time_list) 138 | -------------------------------------------------------------------------------- /chatlog/model/message.py: -------------------------------------------------------------------------------- 1 | from mongoengine import * 2 | 3 | 4 | class Message(Document): 5 | meta = {'db_alias': 'chatlog'} 6 | 7 | name = StringField() # 发言用户昵称 8 | ID = StringField() # 发言用户ID 9 | time = DateTimeField() # 该消息发送时间 10 | text = ListField() # 发送消息的列表 11 | -------------------------------------------------------------------------------- /chatlog/model/user.py: -------------------------------------------------------------------------------- 1 | from mongoengine import * 2 | 3 | 4 | class User(Document): 5 | meta = {'db_alias': 'chatlog'} 6 | 7 | name_now = StringField() # 用户当前昵称 8 | name_list = ListField(StringField) # 用户历史昵称列表 9 | ID = StringField() # ID用户ID 10 | speak_num = IntField() # 用户发言次数 11 | word_num = IntField() # 用户发送文本分词后的词数 12 | photo_num = IntField() # 用户发送图片的数量 13 | ban_num = IntField() # 用户被禁言的次数 14 | ban_time_sum = DateTimeField() # 用户被禁言时间总和 15 | -------------------------------------------------------------------------------- /chatlog/run.py: -------------------------------------------------------------------------------- 1 | from chatlog.analysis.collectivity import Collectivity 2 | from chatlog.analysis.individual import Individual 3 | from chatlog.analysis.interesting import Interesting 4 | from chatlog.base.read_chatlog import ReadChatlog 5 | from chatlog.base.user_profile import UserProfile 6 | 7 | if __name__ == '__main__': 8 | RC = ReadChatlog('./chatlog.txt') 9 | RC.work() # 进行聊天记录的清洗并入库 10 | UP = UserProfile() 11 | UP.work() # 构建简单的用户画像 12 | 13 | # Collectivity 14 | # col = Collectivity() 15 | # print(col.get_all_speak_info()) # 群聊天时间分布 16 | 17 | # Individual 18 | # ind = Individual() 19 | # print(ind.longest_ban()) # 禁言时长的排名 20 | # print(ind.most_speak('speak_num')) # 发言次数的排名 21 | 22 | # Interesting 23 | # interest = Interesting() 24 | # print(interest.longest_formation()) # 最长队形的排名 25 | # print(interest.longest_name()) # 最长的马甲排名 26 | -------------------------------------------------------------------------------- /chatlog/visualization/cat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/chatlog/visualization/cat.png -------------------------------------------------------------------------------- /chatlog/visualization/cat2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/chatlog/visualization/cat2.png -------------------------------------------------------------------------------- /chatlog/visualization/cat3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/chatlog/visualization/cat3.png -------------------------------------------------------------------------------- /chatlog/visualization/charts.py: -------------------------------------------------------------------------------- 1 | # -*- coding=utf-8 -*- 2 | """ 3 | 数据可视化模块 4 | """ 5 | import matplotlib.pyplot as plt 6 | import numpy as np 7 | import pandas as pd 8 | import seaborn as sns 9 | from pymongo import MongoClient 10 | 11 | from chatlog.analysis.individual import Individual 12 | 13 | 14 | class Charts(object): 15 | def __init__(self): 16 | self.client = MongoClient() # 默认连接 localhost 27017 17 | self.db = self.client.chatlog 18 | self.post = self.db.profile 19 | 20 | def ban_time(self): 21 | ind = Individual() 22 | res_list = ind.longest_ban() 23 | res_list = res_list[0:10] 24 | print(res_list) 25 | name_list = [i[1] for i in res_list] 26 | time_list = [i[2] for i in res_list] 27 | 28 | sns.set(style="darkgrid") 29 | plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体 30 | f, ax = plt.subplots(figsize=(18.5, 9)) 31 | 32 | # Plot the crashes where alcohol was involved 33 | sns.set_color_codes("muted") 34 | sns.barplot(x=time_list, y=name_list, 35 | label="禁言时长", color="y") 36 | 37 | # Add a legend and informative axis label 38 | ax.legend(ncol=2, loc="lower right", frameon=True) 39 | ax.set(xlim=(0, time_list[0]), ylabel="", 40 | xlabel="禁言时间最长") 41 | sns.despine(left=True, bottom=True) 42 | 43 | plt.savefig('../photos/ban_time.png', format='png', dpi=400) 44 | plt.close() 45 | 46 | def speak_photo_in_total(self): 47 | """ 48 | 发言次数前10的用户及发送图片的比例 49 | :return: 50 | """ 51 | ind = Individual() 52 | res_list = ind.most_speak('speak_num') 53 | res_list = res_list[0:10] 54 | print(res_list) 55 | ID_list = [i[0] for i in res_list] 56 | name_list = [i[1] for i in res_list] 57 | speak_list = [i[2] for i in res_list] 58 | photo_num = [] 59 | for id in ID_list: 60 | for doc in self.post.find({'ID': id}, {'photo_num': 1}): 61 | photo_num.append(doc['photo_num']) 62 | sns.set(style="darkgrid") 63 | plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体 64 | f, ax = plt.subplots(figsize=(18.5, 9)) 65 | 66 | sns.set_color_codes("pastel") 67 | sns.barplot(x=speak_list, y=name_list, 68 | label="发言次数", color="b") 69 | 70 | # Plot the crashes where alcohol was involved 71 | sns.set_color_codes("muted") 72 | sns.barplot(x=photo_num, y=name_list, 73 | label="发送图片数", color="b") 74 | 75 | # Add a legend and informative axis label 76 | ax.legend(ncol=2, loc="lower right", frameon=True) 77 | ax.set(xlim=(0, speak_list[0]), ylabel="", 78 | xlabel="群里发言次数排行及发送图片的比例") 79 | sns.despine(left=True, bottom=True) 80 | 81 | plt.savefig('../photos/speak_photo_in_total.png', format='png', dpi=300) 82 | plt.close() 83 | 84 | def user_online_time(self, user_ID=None): 85 | """ 86 | 绘制(全体)用户活跃时间图像 87 | :param user_ID:默认为空,指定全体用户,不为空时为指定ID用户 88 | """ 89 | res_list = [] 90 | if user_ID: 91 | find_dict = {'ID': user_ID} 92 | else: 93 | find_dict = {} 94 | 95 | week_online = [[0 for _ in range(24)] for _ in range(7)] 96 | for doc in self.post.find(find_dict, {'week_online': 1}): 97 | for i in range(0, 7): 98 | for j in range(0, 24): 99 | if user_ID: 100 | week_online[i][j] = doc['week_online'][i][j] 101 | else: 102 | week_online[i][j] += doc['week_online'][i][j] 103 | 104 | week_online = np.array([li for li in week_online]) 105 | columns = [str(i) + '-' + str(i + 1) for i in range(0, 24)] 106 | index = ['Mon.', 'Tue.', 'Wed.', 'Thu.', 'Fri.', 'Sat.', 'Sun.'] 107 | 108 | week_online = pd.DataFrame(week_online, index=index, columns=columns) 109 | plt.figure(figsize=(18.5, 9)) 110 | plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体 111 | sns.set() 112 | 113 | # Draw a heatmap with the numeric values in each cell 114 | sns.heatmap(week_online, annot=True, fmt="d", cmap="YlGnBu") 115 | plt.savefig('../photos/user_time_online.png', format='png', dpi=300) 116 | plt.close() 117 | 118 | def close(self): 119 | self.client.close() 120 | 121 | def work(self): 122 | self.speak_photo_in_total() 123 | self.user_online_time() 124 | self.close() 125 | 126 | 127 | if __name__ == '__main__': 128 | chart = Charts() 129 | chart.user_online_time() 130 | -------------------------------------------------------------------------------- /chatlog/visualization/msyh.ttc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/chatlog/visualization/msyh.ttc -------------------------------------------------------------------------------- /chatlog/visualization/word_img.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | import matplotlib.pyplot as plt 4 | import numpy as np 5 | from PIL import Image 6 | from pymongo import MongoClient 7 | from wordcloud import WordCloud, ImageColorGenerator 8 | 9 | 10 | class WordImg(object): 11 | def __init__(self): 12 | self.client = MongoClient() # 默认连接 localhost 27017 13 | self.db = self.client.chatlog 14 | self.post = self.db.word 15 | 16 | def close(self): 17 | self.client.close() 18 | 19 | def draw_wordcloud(self, word_dict, name): 20 | cat_mask = np.array(Image.open('../visualization/cat.png')) 21 | wc = WordCloud(font_path='../visualization/msyh.ttc', 22 | width=800, height=400, 23 | background_color="white", # 背景颜色 24 | mask=cat_mask, # 设置背景图片 25 | min_font_size=6 26 | ) 27 | wc.fit_words(word_dict) 28 | 29 | image_colors = ImageColorGenerator(cat_mask) 30 | # recolor wordcloud and show 31 | # we could also give color_func=image_colors directly in the constructor 32 | plt.imshow(wc) 33 | plt.axis("off") 34 | plt.savefig('../photos/' + name + '.png', dpi=800) 35 | plt.close() 36 | 37 | def PL_wordcloud(self): 38 | word_dict = {'JAVA': ['java', 'jawa'], 'C++': ['c++', 'c艹'], 'C': ['c', 'c语言'], 39 | 'PHP': ['php'], 'Python': ['py', 'python'], 'C#': ['c#']} 40 | self.draw_wordcloud(self.word_fre(word_dict), sys._getframe().f_code.co_name) 41 | 42 | def all_wordcloud(self, word_len=0): 43 | word_dict = {} 44 | stop_word = ['图片', '表情', '说'] 45 | for doc in self.post.find({}): 46 | if len(doc['word']) > word_len and doc['word'] not in stop_word: 47 | word_dict[doc['word']] = doc['item'] 48 | self.draw_wordcloud(word_dict, sys._getframe().f_code.co_name + str(word_len)) 49 | 50 | def company_wordcloud(self): 51 | word_dict = {'Microsoft': ['微软', '巨硬', 'ms', 'microsoft'], 'Tencent': ['腾讯', 'tencent', '鹅厂'], 52 | '360': ['360', '安全卫士', '奇虎'], 'Netease': ['netease', '网易', '猪场'], 53 | 'JD': ['jd', '京东', '某东', '狗东'], 'Taobao': ['淘宝', '天猫', 'taobao'], 54 | 'BaiDu': ['百度', '某度', 'baidu'], 'ZhiHu': ['zhihu', '知乎', '你乎', '某乎'], 55 | 'Sina': ['新浪', 'sina', '微博', 'weibo']} 56 | 57 | self.draw_wordcloud(self.word_fre(word_dict), sys._getframe().f_code.co_name) 58 | 59 | def word_fre(self, word_dict): 60 | word_fre = {} 61 | for key in word_dict.keys(): 62 | word_fre[key] = 0 63 | 64 | res_dict = {} 65 | for doc in self.post.find({}): 66 | res_dict[doc['word']] = doc['item'] 67 | 68 | for res_key in res_dict.keys(): 69 | for word_key in word_dict.keys(): 70 | if str(res_key).lower() in word_dict[word_key]: 71 | word_fre[word_key] = word_fre[word_key] + res_dict[res_key] 72 | 73 | return word_fre 74 | 75 | def longest_formation_wordcloud(self): 76 | word_dict = {} 77 | fp = open('../visualization/list.txt', 'r') 78 | for line in fp.readlines(): 79 | li = line.split(' ') 80 | print(li) 81 | word_dict[li[0]] = int(li[1]) 82 | 83 | wc = WordCloud(font_path='../visualization/msyh.ttc', 84 | width=1080, height=720, 85 | background_color="white", # 背景颜色 86 | min_font_size=6 87 | ) 88 | wc.fit_words(word_dict) 89 | plt.imshow(wc) 90 | plt.axis("off") 91 | plt.savefig('../photos/' + sys._getframe().f_code.co_name + '.png', dpi=800) 92 | plt.show() 93 | plt.close() 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | def work(self): 102 | self.PL_wordcloud() 103 | self.company_wordcloud() 104 | self.all_wordcloud() 105 | self.close() 106 | 107 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /photos/PL_wordcloud.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/photos/PL_wordcloud.png -------------------------------------------------------------------------------- /photos/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/photos/README.md -------------------------------------------------------------------------------- /photos/all_wordcloud0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/photos/all_wordcloud0.png -------------------------------------------------------------------------------- /photos/all_wordcloud1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/photos/all_wordcloud1.png -------------------------------------------------------------------------------- /photos/all_wordcloud2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/photos/all_wordcloud2.png -------------------------------------------------------------------------------- /photos/all_wordcloud3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/photos/all_wordcloud3.png -------------------------------------------------------------------------------- /photos/company_wordcloud.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/photos/company_wordcloud.png -------------------------------------------------------------------------------- /photos/speak_photo_in_total.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/photos/speak_photo_in_total.png -------------------------------------------------------------------------------- /photos/user_time_online.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DingHanyang/chatLog/2ac503faa3fd48019e5ddffbc5d37e54f8f30f25/photos/user_time_online.png --------------------------------------------------------------------------------