用python玩微信(聊天机器人,好友信息统计)

1.用 Python 实现微信好友性别及位置信息统计

这里使用的python3+wxpy库+Anaconda(Spyder)开发。如果你想对wxpy有更深的了解请查看:wxpy: 用 Python 玩微信

# -*- coding: utf-8 -*-
"""
微信好友性别及位置信息
"""

#导入模块
from wxpy import Bot

'''Q
微信机器人登录有3种模式,
(1)极简模式:robot = Bot()
(2)终端模式:robot = Bot(console_qr=True)
(3)缓存模式(可保持登录状态):robot = Bot(cache_path=True)
'''
#初始化机器人,选择缓存模式(扫码)登录
robot = Bot(cache_path=True)

#获取好友信息
robot.chats()
#robot.mps()#获取微信公众号信息

#获取好友的统计信息
Friends = robot.friends()
print(Friends.stats_text())
复制代码

效果图(来自笔主盆友圈):

2.用 Python 实现聊天机器人

这里使用的python3+wxpy库+Anaconda(Spyder)开发。需要提前去图灵官网创建一个属于自己的机器人然后得到apikey。

  • 使用图灵机器人自动与指定好友聊天

让室友帮忙测试发现发送表情发送文字还能回应,但是发送图片可能不会回复,猜应该是我们申请的图灵机器人是最初级的没有加图片识别功能。

# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 19:09:05 2018

@author: Snailclimb
@description使用图灵机器人自动与指定好友聊天
"""

from wxpy import Bot,Tuling,embed,ensure_one
bot = Bot()
my_friend = ensure_one(bot.search('郑凯'))  #想和机器人聊天的好友的备注
tuling = Tuling(api_key='你申请的apikey')
@bot.register(my_friend)  # 使用图灵机器人自动与指定好友聊天
def reply_my_friend(msg):
    tuling.do_reply(msg)
embed()
复制代码
  • 使用图灵机器人群聊
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 18:55:04 2018

@author: Administrator
"""

from wxpy import Bot,Tuling,embed
bot = Bot(cache_path=True)
my_group = bot.groups().search('群聊名称')[0]  # 记得把名字改成想用机器人的群
tuling = Tuling(api_key='你申请的apikey')  # 一定要添加,不然实现不了
@bot.register(my_group, except_self=False)  # 使用图灵机器人自动在指定群聊天
def reply_my_friend(msg):
    print(tuling.do_reply(msg))
embed()
复制代码

3.用 Python分析朋友圈好友性别分布(图标展示)

这里没有使用wxpy而是换成了Itchat操作微信,itchat只需要2行代码就可以登录微信。如果你想详细了解itchat,请查看: itchat入门进阶教程以及 itchat github项目地址 另外就是需要用到python的一个画图功能非常强大的第三方库:matplotlib。 如果你想对matplotlib有更深的了解请查看我的博文:Python第三方库matplotlib(词云)入门与进阶

# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 17:09:26 2018

@author: Snalclimb
@description 微信好友性别比例
"""

import itchat
import matplotlib.pyplot as plt
from collections import Counter
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)
sexs = list(map(lambda x: x['Sex'], friends[1:]))
counts = list(map(lambda x: x[1], Counter(sexs).items()))
labels = ['Male','FeMale',   'Unknown']
colors = ['red', 'yellowgreen', 'lightskyblue']
plt.figure(figsize=(8, 5), dpi=80)
plt.axes(aspect=1)
plt.pie(counts,  # 性别统计结果
        labels=labels,  # 性别展示标签
        colors=colors,  # 饼图区域配色
        labeldistance=1.1,  # 标签距离圆点距离
        autopct='%3.1f%%',  # 饼图区域文本格式
        shadow=False,  # 饼图是否显示阴影
        startangle=90,  # 饼图起始角度
        pctdistance=0.6  # 饼图区域文本距离圆点距离
)
plt.legend(loc='upper right',)
plt.title('%s的微信好友性别组成' % friends[0]['NickName'])
plt.show()
复制代码

效果图(来自笔主盆友圈):

4.用 Python分析朋友圈好友的签名

需要用到的第三方库:

numpy:本例结合wordcloud使用

jieba对中文惊进行分词

PIL: 对图像进行处理(本例与wordcloud结合使用)

snowlp对文本信息进行情感判断

wordcloud生成词云 matplotlib:绘制2D图形

# -*- coding: utf-8 -*-
"""
朋友圈朋友签名的词云生成以及
签名情感分析
"""
import re,jieba,itchat
import jieba.analyse
import numpy as np
from PIL import Image
from snownlp import SnowNLP
from wordcloud import WordCloud
import matplotlib.pyplot as plt
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)
def analyseSignature(friends):
    signatures = ''
    emotions = []
    for friend in friends:
        signature = friend['Signature']
        if(signature != None):
            signature = signature.strip().replace('span', '').replace('class', '').replace('emoji', '')
            signature = re.sub(r'1f(\d.+)','',signature)
            if(len(signature)>0):
                nlp = SnowNLP(signature)
                emotions.append(nlp.sentiments)
                signatures += ' '.join(jieba.analyse.extract_tags(signature,5))
    with open('signatures.txt','wt',encoding='utf-8') as file:
         file.write(signatures)

    # 朋友圈朋友签名的词云相关属性设置
    back_coloring = np.array(Image.open('alice_color.png'))
    wordcloud = WordCloud(
        font_path='simfang.ttf',
        background_color="white",
        max_words=1200,
        mask=back_coloring, 
        max_font_size=75,
        random_state=45,
        width=1250, 
        height=1000, 
        margin=15
    )
    
    #生成朋友圈朋友签名的词云
    wordcloud.generate(signatures)
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()
    wordcloud.to_file('signatures.jpg')#保存到本地文件

    # Signature Emotional Judgment
    count_good = len(list(filter(lambda x:x>0.66,emotions)))#正面积极
    count_normal = len(list(filter(lambda x:x>=0.33 and x<=0.66,emotions)))#中性
    count_bad = len(list(filter(lambda x:x<0.33,emotions)))#负面消极
    labels = [u'负面消极',u'中性',u'正面积极']
    values = (count_bad,count_normal,count_good)
    plt.rcParams['font.sans-serif'] = ['simHei'] 
    plt.rcParams['axes.unicode_minus'] = False
    plt.xlabel(u'情感判断')#x轴
    plt.ylabel(u'频数')#y轴
    plt.xticks(range(3),labels)
    plt.legend(loc='upper right',)
    plt.bar(range(3), values, color = 'rgb')
    plt.title(u'%s的微信好友签名信息情感分析' % friends[0]['NickName'])
    plt.show()
analyseSignature(friends)
复制代码

效果图(来自笔主盆友圈):

参考文献:

itchat文档:itchat.readthedocs.io/zh/latest/t…

wxpy文档:wxpy.readthedocs.io/zh/latest/i…

基于Python实现的微信好友数据分析(签名,头像等等): blog.csdn.net/qinyuanpei/…

Windows环境下Python中wordcloud的使用——自己踩过的坑 :blog.csdn.net/heyuexianzi…

欢迎关注我的微信公众号(分享各种Java学习资源,面试题,以及企业级Java实战项目回复关键字免费领取):

github项目地址(系列文章包含常见第三库的使用与爬虫,会持续更新) 欢迎star和fork.

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值