个项目包含三个主要文件,实现微信好友统计的完整功能。主程序通过itchat库获取好友数据,使用SQLite存储历史记录,并生成可视化报告和文本统计。定时任务脚本可实现自动化每日统计。
下载地址:http://m.pan38.com/download.php?code=ABWZFT 访问密码(可选):6666
代码语言:txt复制
import itchat
import time
import sqlite3
from datetime import datetime
import matplotlib.pyplot as plt
import pandas as pd
class WeChatFriendCounter:
def __init__(self):
self.db_name = "friend_stats.db"
self.init_db()
def init_db(self):
conn = sqlite3.connect(self.db_name)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS friends
(date TEXT PRIMARY KEY,
total INTEGER,
male INTEGER,
female INTEGER,
unknown_gender INTEGER,
province_stats TEXT)''')
conn.commit()
conn.close()
def login(self):
itchat.auto_login(hotReload=True,
statusStorageDir='wx_counter.pkl',
enableCmdQR=2)
print("登录成功,开始统计好友信息...")
def analyze_friends(self):
friends = itchat.get_friends(update=True)[1:] # 排除自己
total = len(friends)
male = len([f for f in friends if f['Sex'] == 1])
female = len([f for f in friends if f['Sex'] == 2])
unknown = len([f for f in friends if f['Sex'] == 0])
provinces = {}
for f in friends:
province = f['Province'] if f['Province'] else '未知'
provinces[province] = provinces.get(province, 0) + 1
return {
'date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'total': total,
'male': male,
'female': female,
'unknown_gender': unknown,
'province_stats': str(provinces)
}
def save_to_db(self, stats):
conn = sqlite3.connect(self.db_name)
c = conn.cursor()
c.execute("INSERT OR REPLACE INTO friends VALUES (?,?,?,?,?,?)",
(stats['date'], stats['total'], stats['male'],
stats['female'], stats['unknown_gender'],
stats['province_stats']))
conn.commit()
conn.close()
def generate_report(self):
conn = sqlite3.connect(self.db_name)
df = pd.read_sql("SELECT * FROM friends ORDER BY date", conn)
conn.close()
plt.figure(figsize=(12, 6))
plt.plot(pd.to_datetime(df['date']), df['total'], 'b-o')
plt.title('微信好友增长趋势')
plt.xlabel('日期')
plt.ylabel('好友数量')
plt.grid(True)
plt.savefig('friend_growth.png')
with open('friend_report.txt', 'w') as f:
f.write(f"=== 微信好友统计报告 ===\n")
f.write(f"统计时间: {datetime.now()}\n")
f.write(f"当前好友总数: {df.iloc[-1]['total']}\n")
f.write(f"男性好友: {df.iloc[-1]['male']}\n")
f.write(f"女性好友: {df.iloc[-1]['female']}\n")
f.write(f"未设置性别: {df.iloc[-1]['unknown_gender']}\n")
f.write("\n=== 省份分布 ===\n")
provinces = eval(df.iloc[-1]['province_stats'])
for p, cnt in sorted(provinces.items(), key=lambda x: -x[1]):
f.write(f"{p}: {cnt}\n")
def run(self):
self.login()
stats = self.analyze_friends()
self.save_to_db(stats)
self.generate_report()
print("统计完成!报告已生成到friend_report.txt和friend_growth.png")
if __name__ == '__main__':
counter = WeChatFriendCounter()
counter.run()
itchat>=1.3.10
matplotlib>=3.3.0
pandas>=1.1.0
sqlite3>=2.6.0
代码语言:txt复制import schedule
import time
from wechat_counter import WeChatFriendCounter
def job():
print("开始每日微信好友统计...")
counter = WeChatFriendCounter()
counter.run()
print("统计任务完成")
# 每天上午10点执行
schedule.every().day.at("10:00").do(job)
while True:
schedule.run_pending()
time.sleep(60)