QQ聊天记录词云

读取QQ聊天记录,分词后基于词频制作词云

下面是实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import numpy as np
from tqdm import tqdm
import jieba
import wordcloud
import re
from PIL import Image

data = []
with open('01.txt','r',encoding='utf-8')as f://读取导出后的聊天记录
for line in tqdm(f.readlines()):
line = line.strip()
if len(line) == 0:
continue
if line[-1] == '-' or line[-1] == '.':
data.append(line[-1])
else:
data.append(line)

d1, d2 = [], []
for i in tqdm(range(len(data)//2))://将两人的文本分别预处理后存储到list中
if data[2*i] == '.':
if data[2 * i + 1] == '[图片]':
continue
tmp = jieba.lcut(re.sub(r'[^\w\s]', '', data[2 * i + 1].replace('[表情]', '')))
d1.extend(tmp)
elif data[2*i] == '-':
if data[2 * i + 1] == '[图片]':
continue
tmp = jieba.lcut(re.sub(r'[^\w\s]', '', data[2 * i + 1].replace('[表情]', '')))
d2.extend(tmp)

d1 = ' '.join(d1)
d2 = ' '.join(d2)

mask = np.array(Image.open('mask.png'))//使用爱心形状的遮罩
w1 = wordcloud.WordCloud(mask=mask, font_path="FZQiTi-S14S.TTF", background_color='white')//制作词云
w1.generate(d1)
w1.to_file("1.png")
w2 = wordcloud.WordCloud(mask=mask, font_path="FZQiTi-S14S.TTF", background_color='white')
w2.generate(d2)
w2.to_file("2.png")

用到的遮罩

用到的遮罩

嘿嘿,大功告成~

我的

我的

宝贝的

宝贝的