Python使用itchat获取微信好友

简介: 最近发现了一个好玩的包itchat,通过调用微信网页版的接口实现收发消息,获取好友信息等一些功能,各位可以移步itchat项目介绍查看详细信息。目标:获取好友列表统计性别及城市分布根据好友签名生成词云获取好友信息前文说了,itchat其实是调用微信网页版的接口,所以登陆的时候会弹出二维码进行登陆,然后通过itchat.get_friends获取好友信息就好了,相当简单。

最近发现了一个好玩的包itchat,通过调用微信网页版的接口实现收发消息,获取好友信息等一些功能,各位可以移步itchat项目介绍查看详细信息。

目标:

  • 获取好友列表
  • 统计性别及城市分布
  • 根据好友签名生成词云

获取好友信息

  • 前文说了,itchat其实是调用微信网页版的接口,所以登陆的时候会弹出二维码进行登陆,然后通过itchat.get_friends获取好友信息就好了,相当简单。
# -*- coding: utf-8 -*-
import itchat
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
import jieba
import re
from scipy.misc import imread  
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
itchat.login()
#登陆网页版微信,需要手机扫码确认
warnings.filterwarnings("ignore")
  • 获取好友信息的时候需要注意一点,因为好友列表中第一位是自己,所以从第二位开始保存。
friends = itchat.get_friends(update=True)
for counter,content in enumerate(friends[1:]):
    if counter == 0:
        df=pd.DataFrame(content)
        df.columns=content.keys()
    else:
        df.loc[counter]=content.values()
print '获取到%d位好友信息'%counter
df.columns
  • 字段信息如下:
Index([u'UserName', u'City', u'DisplayName', u'UniFriend', u'MemberList',
       u'PYQuanPin', u'RemarkPYInitial', u'Sex', u'AppAccountFlag',
       u'VerifyFlag', u'Province', u'KeyWord', u'RemarkName', u'PYInitial',
       u'IsOwner', u'ChatRoomId', u'HideInputBarFlag', u'EncryChatRoomId',
       u'AttrStatus', u'SnsFlag', u'MemberCount', u'OwnerUin', u'Alias',
       u'Signature', u'ContactFlag', u'NickName', u'RemarkPYQuanPin',
       u'HeadImgUrl', u'Uin', u'StarFriend', u'Statues'],
      dtype='object')

好友城市分布

  • 因为微信中位置信息是两级,省份和城市,对于北京上海这种直辖市,City字段中保存的是区的信息,这个部分做了下处理改为相应的城市名。
df['City'][df['Province']==u'北京']= u'北京'
df['City'][df['Province']==u'上海']= u'上海'
df['City'][df['Province']==u'重庆']= u'重庆'
#微信对于直辖市将city字段填写为区
plt.figure(figsize = (15,12))
data_temp = df[df['City']!='']
#剔除城市未填写的记录
data_temp = data_temp.groupby(['City'])['UserName'].count().reset_index()
data_temp = data_temp.nlargest(15,'UserName')
data_temp.columns = ['City','Count']
sns.barplot(data=data_temp ,y='City',x='Count')
for y,x in enumerate(data_temp['Count']):
    plt.text(x,y,x,fontsize = 20)
plt.title(u'好友城市分布',fontsize =25)
plt.show()
  • 只取了前15位,效果如下:


    img_ca370230b2ebbac932dddd28c9a38552.png

性别分布

  • Sex字段中有0,1,2三个值,分别代表性别不明,男,女,相应的replace一下就好。
df['Sex'] = df['Sex'].replace({0:u'性别不明',1:u'男',2:u'女'})
plt.figure(figsize = (15,8))
plt.subplot(1,2,1)
data_temp = df.groupby(['Sex'])['UserName'].count().reset_index()
data_temp = data_temp.sort_values('UserName')
data_temp.columns = ['Sex','Count']
sns.barplot(data=data_temp ,x='Sex',y='Count')
for x,y in enumerate(data_temp['Count']):
    plt.text(x-0.05,y,y,fontsize = 20)
plt.subplot(1,2,2)
sex_list = [u'男',u'女',u'性别不明']
countlist = [292,227,25]
explode = (0.05,0,0)
plt.pie(countlist,labels = sex_list,explode =explode,startangle = 90,autopct = '%3.1f%%')
plt.axis('equal')
plt.show()
  • 效果如下:


    img_454f8d99d0b3d807c039f091602c8084.png

根据好友签名绘制词云

  • Signature中保存的是好友签名,开始试了一次,发现签名中emoji表情占了好大的比例,后面用正则表达式处理了下,只保留了汉字部分。
back_color = imread('tencent.jpg')  # 解析该图片
wc = WordCloud(background_color='white',  # 背景颜色
               max_words=1000,  # 最大词数
               mask=back_color,  # 以该参数值作图绘制词云,这个参数不为空时,width和height会被忽略
               max_font_size=100,  # 显示字体的最大值
               font_path="/Users/tangwenpan/Downloads/simhei.ttf",  # 解决显示口字型乱码问题
               random_state=42,  # 为每个词返回一个PIL颜色
               )

text=''
xx= u"[\u4e00-\u9fa5]" #保留汉字
for x in df['Signature']:
    pattern = re.compile(xx)  
    text_temp =  pattern.findall(x) 
    for xxx in text_temp:
        text = text +xxx

def word_cloud(texts):
    words_list = []
    word_generator = jieba.cut(texts, cut_all=False)  # 返回的是一个迭代器
    for word in word_generator:
        if len(word) > 1:  #去掉单字
            words_list.append(word)
    return ' '.join(words_list)  


text = word_cloud(text)

wc.generate(text)
# 基于彩色图像生成相应彩色
image_colors = ImageColorGenerator(back_color)
plt.figure(figsize = (15,15))
plt.axis('off')
# 绘制词云
plt.imshow(wc.recolor(color_func=image_colors))
plt.axis('off')
# 保存图片
wc.to_file('comment.png')
print 'comment.png has bee saved!'
  • 使用背景图片


    img_9ff6d859a03ea669c33d3b4eeb303e84.png
  • 效果如下:


    img_fe5b2951ac710f138c5b36bd343a2e86.png

peace~

目录
相关文章
|
1月前
|
数据采集 测试技术 API
python爬虫之app爬取-微信朋友圈
搭建appium环境,appium基本使用,API操作等等
80 0
|
3天前
|
数据采集 存储 人工智能
【Python+微信】【企业微信开发入坑指北】4. 企业微信接入GPT,只需一个URL,自动获取文章总结
【Python+微信】【企业微信开发入坑指北】4. 企业微信接入GPT,只需一个URL,自动获取文章总结
13 0
|
3天前
|
人工智能 机器人 API
【Python+微信】【企业微信开发入坑指北】3. 如何利用企业微信API给微信群推送消息
【Python+微信】【企业微信开发入坑指北】3. 如何利用企业微信API给微信群推送消息
6 0
|
3天前
|
缓存 人工智能 API
【Python+微信】【企业微信开发入坑指北】2. 如何利用企业微信API主动给用户发应用消息
【Python+微信】【企业微信开发入坑指北】2. 如何利用企业微信API主动给用户发应用消息
7 0
|
3天前
|
Linux 网络安全 开发工具
【超详细!超多图!】【代码管理】Python微信公众号开发(3)- 服务器代码上传Github
【超详细!超多图!】【代码管理】Python微信公众号开发(3)- 服务器代码上传Github
10 0
|
7天前
|
小程序
uniapp 实现当前页面分享至微信好友或朋友圈功能(带参数和无参数)
uniapp 实现当前页面分享至微信好友或朋友圈功能(带参数和无参数)
8 0
|
1月前
|
数据采集 存储 关系型数据库
Python爬虫-使用代理获取微信公众号文章
使用代理爬取微信公众号文章
54 0
|
1月前
|
监控 安全 API
怎么用Python找回微信撤回信息
怎么用Python找回微信撤回信息
34 0
|
存储 API 定位技术
想查看微信好友撤回的消息?Python帮你搞定
想查看微信好友撤回的消息?Python帮你搞定
712 1
想查看微信好友撤回的消息?Python帮你搞定
|
1天前
|
机器学习/深度学习 人工智能 数据可视化
Python:探索编程之美
Python:探索编程之美
9 0