您的位置:首页 > 编程语言 > Python开发

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

2018-03-16 08:44 1026 查看

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)


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





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

欢迎star和fork.

如果你觉得博主的文章不错,欢迎转发点赞。你能从中学到知识就是我最大的幸运。

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: