编程秘技,用python玩转微信好友 !

微信作为一个老少咸宜的聊天工具,它是我们生活中真实朋友圈的网络数据版本,而我们可曾想过将微信的数据进行整理归纳统计,从而发现自己朋友圈的秘密和交友习惯、生活方式的蛛丝马迹?微信上的昵称、签名、地区由文字来表达,它们在python中就被利用为文本数据,通过对这些文本数据进行挖掘分析,我们就能清晰地发现一些有趣的秘密……如果你也对隐藏在文本和符号之下的讯息感兴趣,对你自己的交友圈想要一探究竟,那么就一起来看看下面的操作吧!

首先介绍一下我们我们所利用的工具:itchat,itchat是一个开源的微信个人号接口,使用它我们可以方便迅速地访问我们个人微信号里的信息。

想要使用itchat库,我们先进行安装和引用:

pip install itchatimport itchat

之后我们登录自己的微信:

itchat.auto_login

执行后,会在当前目录下生成一个二维码图片文件并自动弹出,这时可以用手机微信扫描二维码,手机确认后即可登陆至电脑,终端会提示登陆成功,登陆成功后生成的二维码也会自动消失。

很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。

很多已经做案例的人,却不知道如何去学习更加高深的知识。

那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!

QQ群:701698587

然而我在实验的过程中,却遇到了如下情况:

图片

我重复、重启、换电脑,怎么折腾都还是登录失败,在网上浏览了很多帖子,发现有不少人跟我一样遇到因为“账户安全”而无法登陆的问题,可是有的微信号就没有这种问题,似乎本质上是我的微信无法登陆网页版的问题,跟python无关,各方也没有什么好的解决办法,无奈之下我只得自认倒霉,借用了别的好友的微信来操作。

(假如)登陆成功后,为了制造乐趣,我们首先尝试一下用代码发微信消息,:

#输入ta的备注users = itchat.search_friends("郑晓玥")userName = users[0]['UserName']print(userName)#打印确认无误后,输入信息itchat.send(msg="嘎嘎嘎,在吗", toUserName=userName)我们还可以给自己发消息:itchat.send(msg="我是猪 ")

简单的操作,但是经本人亲试证明乐趣无穷。

图片

好了,接下来进入正经的统计环节,首先为了有个宏观的概览,我们可以试着提取所有好友的所有信息(昵称、签名、地理位置等),并将它存放在Excel文件里,操作代码如下:

# Write information.table.write(0, 5, u’)table.write(0, 7, u')table.write(0, 0, u'【昵称】')table.write(0, 1, u'【备注名】')table.write(0, 2, u'【省份】')table.write(0, 3, u'【城市】')table.write(0, 4, u'【签名】')# Loop writing.a = 0for i in friends:    table.write(a+1, 0, i['NickName'])    table.write(a+1, 1, i['RemarkName'])    table.write(a+1, 2, i['Province'])    table.write(a+1, 3, i['City'])table.write(a+1, 4, i['Signature'])    if i['RemarkName'] == u'':        table.write(a+1, 1, u'[ ]')    if i['Province'] == u'':        table.write(a+1, 2, u'[ ]')    if i['City'] == u'':        table.write(a+1, 3, u'[ ] ')    if i['Signature'] == u'':        table.write(a+1, 4, u'[ ] ')    a = a+1# Name:“weixin_20190000.xls”将结果以Excel形式保存aaa = 'weixin_'+time.strftime("%Y%m%d", time.localtime())+'.xls'file.save(aaa)# Send to filehelper.itchat.send('made by persimmon', 'filehelper')itchat.send('@%s@%s' % ('fil', aaa), 'filehelper')print("over")

然后我们就可以从我们的工作路径发现一个数据齐全但庞杂混乱的Excel文件,但是这并不能得出什么有用结论。接下来就让我们分不同的模块操作,深入探寻好友圈的秘密(滑稽.jpg)。

一、微信好友男女比例

首先我们最感兴趣的、也最好操作的当然是男女数量之比了。

先获取好友列表:

friends = itchat.get_friends(update=True)[0:]

然后开始对男女数量开始循环累加计算(注意因为有些人没有注明自己的性别,这里要分为三类):

#初始化计算器male = female = others = 0for i in friends[0:]:    sex = i["Sex"]    if sex == 1:        male += 1    elif sex == 2:        female += 1    else:        others += 1#以浮点数形式表示数据total = len(friends[0:])num_1 = float(male)num_2 = float(female)num_3 = float(others)#打印结果print(total)print(num_1)print(num_2)print(num_3)接下来计算男女比例:total = len(friends[1:])  # 总数,男,女,其他num1 = float(male) / total * 100num2 = float(female) / total * 100num3 = float(others) / total * 100print("   的微信好友数:" + str(total))  # 输出print("男性好友比例:" + str(num1) + "%" + "\n" + "数量:" + str(float(male)))print("女性好友比例:" + str(num2) + "%" + "\n" + "数量:" + str(float(female)))print("未填性别:" + str(num3) + "%" + "\n" + "数量" + str(float(others)))

得到结果:

的微信好友数:264

男性好友比例:27.65151515151515%

数量:73.0

女性好友比例:56.439393939393945%

数量:149.0

未填性别:15.909090909090908%

数量42.0

(咳咳,这是一位妹子的微信ヽ(*。>Д<)o゜)

如果我们想让数据更加可视化,那么我们就可以利用numpy包实现图表创造:

import numpy as npimport matplotlib.pyplot as pltlabels ='male','female','other'#各组标签命名fraces = [73,149,42]#输入数据plt.axes(aspect=1)plt.pie(x=fraces,labels= labels,autopct='%0f%%')#显示各组百分比plt.pie(x=fraces,labels= labels)plt.show()

结果如下:

图片

二、好友个性签名词云

词云是个非常神奇有趣的东西,现在我们就来试试用自己的好友签名生成词云!首先还是重复之前的登录并获取好友列表操作,之后:

for i in friends:        signature = i["Signature"]# 获取个性签名print signature# 打印个性签名

打印之后你会发现,有大量的class,emoji,等碍眼的字段,因为个性签名中使用了表情符号,这些字段都是要过滤掉的:

for i in friends:    signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji", "")    rep = re.compile("1f\d.+")    signature = rep.sub("", signature)    print signature

接来下用jieba分词,然后制作成词云,首先要安装jieba和wordcloud库

pip install jiebapip install wordcloudimport itchatimport re# coding:utf-8itchat.login()friends = itchat.get_friends(update=True)[0:]tList = []for i in friends:    signature = i["Signature"].replace(" ", "").replace("span", "").replace("class", "").replace("emoji", "")    rep = re.compile("1f\d.+")    signature = rep.sub("", signature)    tList.append(signature)text = "".join(tList) # 拼接字符串import jiebawordlist_jieba = jieba.cut(text, cut_all=True)wl_space_split = " ".join(wordlist_jieba) # jieba分词import matplotlib.pyplot as pltfrom wordcloud import WordCloudimport PIL.Image as Image# wordcloud词云my_wordcloud = WordCloud(background_color="white", max_words=2000,                          max_font_size=40, random_state=42,                         font_path='/Users/sebastian/Library/Fonts/Arial Unicode.ttf').generate(wl_space_split)plt.imshow(my_wordcloud)plt.axis("off")plt.show()

三、好友地理分布图绘制

想要知道自己的朋友都来自于哪里?那就来试试用获取的好友省份市区绘制地图!

# map-distributionProvince = get_var('Province')data = pd.DataFrame({'prv':Province, 'nu':1})data = data.loc[data['prv']!='', :]data = data.groupby(['prv']).sum().sort_values(by='nu')province = data.index.tolist()values = data.values.tolist()C = Collector()@C.funcsdef map_base() -> Map:    c = (Map().add("", [list(z) for z in zip(province, values)], "china")        .set_global_opts(title_opts=opts.TitleOpts(title="微信好友地区分布(连续型)"), visualmap_opts=opts.VisualMapOpts(max_=50)    return cPage().add(*[fn() for fn, _ in C.charts]).render("map-distribution of friends.html")# analyse signature# it has some unknown mistake.siglist = []for i in friends:    signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji", "")    rep = re.compile("1f\d+\w*|[<>/=]")    signature = rep.sub("", signature)    siglist.append(signature)text = "".join(siglist)wordlist = jieba.cut(text, cut_all=True)word_space_split = ",".join(wordlist).split(',')m = []for i in word_space_split:    m.append(i)da = pd.DataFrame({'ci':m, 'nu':1})da = da.groupby(['ci']).sum().sort_values(by='nu', ascending=False)da.to_csv('d:/qianming.csv')# Preserve images that were used by my friends into local computerusername = get_var('UserName')for i, uname in enumerate(username):    with open("headImg/"+str(i)+".png", "wb") as f:        img = itchat.get_head_img(uname)        f.write(img)x = 0y = 0imgs = os.listdir("headImgs")random.shuffle(imgs)input_lengh = int(input("2160"))input_width = int(input("1080"))new_img = Image.new('RGBA', (input_width, input_lengh))width = int(math.sqrt(input_lengh * input_width / len(imgs)))num_line = int(input_width/width)for i in imgs:    try:        img = Image.open("headImage/" + i)    except IOError:        print("第{}张图片为空".format(i))    else:        img = img.resize((width, width),   Image.ANTIALIAS)        new_img.paste(img, (x * width, y * width))        x += 1        if x >= num_line:            x = 0            y += 1new_img.save("mixImg.png")itchat.send_image('mixedImg.png')

对微信好友的(神wu奇yong)分析就到这里了!还有自动回复、好友聊天频次统计、生成好友头像集合图、找回被撤回消息、查找谁删过自己……等无限功能等待着大家利用python和itchat库自由探索。

图片

猜你喜欢

转载自blog.csdn.net/Python_kele/article/details/115057214
今日推荐