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

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

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

# -*- 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())
复制代码

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

位置信息

2.用 Python 实现聊天机器人

这里使用的python3+wxpy库+Anaconda(Spyder)开发。须要提早去图灵官网建立一个属于本身的机器人而后获得apikey。git

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

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

# -*- 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()
复制代码

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

盆友圈性别分布

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

须要用到的第三方库:缓存

numpy:本例结合wordcloud使用微信

jieba对中文惊进行分词app

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

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实战项目回复关键字免费领取):

image

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

相关文章
相关标签/搜索