事情的起因很偶然
女朋友手机坏了,聊天记录备份到我电脑上。我本想帮她恢复,却手贱点开了导出文件。看着几万条消息,我突然好奇:如果分析一下,会不会有什么有趣的发现?说干就干,打开PyCharm。
数据导出来有点乱
微信的备份格式不好直接读。我用了一个开源工具转成txt,每行一条消息,带时间戳和发送人。清理了一下,一共三万七千条。时间跨度两年。数据量不小。
# 读取聊天记录文件
import re
from collections import Counter
messages = []
with open('chat_history.txt', 'r', encoding='utf-8') as f:
for line in f:
# 解析格式: 2023-01-15 20:30 小明: 今晚吃什么
match = re.match(r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}) (.+?): (.+)', line)
if match:
time_str, sender, content = match.groups()
messages.append({'time': time_str, 'sender': sender, 'content': content})
print(f"共加载 {len(messages)} 条消息")
第一个发现:她发的消息比我多
统计了一下,她发了两万条,我一万七。平均每天她发27条,我23条。看来她更话痨一点。我把这个结论告诉她,她白了我一眼:那是因为你老不回。😂
# 统计发送频率
senders = Counter([m['sender'] for m in messages])
print(f"消息数统计: {senders}")
# 平均每日消息量
from datetime import datetime
days = (datetime.strptime(messages[-1]['time'], '%Y-%m-%d %H:%M') -
datetime.strptime(messages[0]['time'], '%Y-%m-%d %H:%M')).days
print(f"平均每天 {len(messages)/days:.1f} 条")
第二个发现:深夜消息有猫腻
我把消息按小时分布做了统计。晚上十一点到凌晨一点,她的消息量暴增。我以为是熬夜刷剧。仔细看内容,全是在跟闺蜜吐槽我。什么"他又打游戏不理我""袜子乱扔"。看得我汗流浃背。
import matplotlib.pyplot as plt
hours = [datetime.strptime(m['time'], '%Y-%m-%d %H:%M').hour for m in messages]
hour_counts = Counter(hours)
plt.bar(hour_counts.keys(), hour_counts.values(), color='pink')
plt.xlabel('小时')
plt.ylabel('消息数')
plt.title('聊天时间分布')
plt.savefig('hour_dist.png')
第三个发现:她最常用的词
用jieba做了分词,去掉了"的""了""是"这些停用词。词云出来的那一刻,我愣了。最大的几个字是:"吃饭""好累""哈哈哈""想你"。最后那个词,让我心里软了一下。
import jieba
from wordcloud import WordCloud
all_text = ' '.join([m['content'] for m in messages if m['sender'] == '女朋友'])
words = jieba.lcut(all_text)
# 过滤停用词
stopwords = set(['的', '了', '是', '我', '你', '在', '吧'])
words = [w for w in words if len(w) > 1and w notin stopwords]
# 生成词云
wordcloud = WordCloud(font_path='msyh.ttc', width=800, height=400,
background_color='white').generate(' '.join(words))
wordcloud.to_file('wordcloud.png')
第四个发现:吵架有规律
我搜了"哼""烦""算了""不想说"这些关键词。发现每个月的十五号前后,出现频率明显偏高。后来我恍然大悟,那是她来例假的日子。原来激素才是幕后黑手。🤔
# 搜索情绪关键词
angry_words = ['哼', '烦', '算了', '不想说', '随便你']
angry_msgs = [m for m in messages if any(w in m['content'] for w in angry_words)]
print(f"含情绪词的消息共 {len(angry_msgs)} 条")
for m in angry_msgs[-5:]:
print(f"{m['time']}{m['sender']}: {m['content']}")
第五个发现:意想不到的秘密
我把两年的"想你""爱你""抱抱"这些词按月统计。发现热恋期前六个月,数量高得离谱。之后逐渐平稳。但有个例外:我出差那两个月,数量突然反弹。原来距离真的能产生美。
# 甜蜜词月度统计
sweet_words = ['想你', '爱你', '抱抱', '亲亲']
monthly_sweet = {}
for m in messages:
month = m['time'][:7] # 取年月
if month notin monthly_sweet:
monthly_sweet[month] = 0
if any(w in m['content'] for w in sweet_words):
monthly_sweet[month] += 1
print("月度甜蜜指数:")
for month, count in sorted(monthly_sweet.items()):
print(f"{month}: {'❤' * count}")
我把分析结果给她看了
她一开始骂我侵犯隐私。但看到词云里"想你"两个字最大的时候,她笑了。然后指着深夜吐槽我的记录,拧了我一把。疼,但值得。
技术栈其实很简单
jieba分词 + wordcloud画图 + matplotlib做图表 + pandas做统计。没什么高深的。但有数据支撑的分析,比凭感觉聊天有意思多了。
# 情感分析小彩蛋
from snownlp import SnowNLP
sample = messages[-100:]
sentiments = [SnowNLP(m['content']).sentiments for m in sample]
avg = sum(sentiments) / len(sentiments)
print(f"最近100条消息的平均情感值: {avg:.2f}")
print(">0.6偏正面,<0.4偏负面,中间是中性")