微信API接口应用及可视化数据分析

from os import path
import re, jieba
import matplotlib.font_manager as fm
from pylab import *
from wxpy import *
import re, jieba
import matplotlib.pyplot as plt
#词云生成工具
from wordcloud import WordCloud,ImageColorGenerator
#需要对中文进行处理
import matplotlib.font_manager as fm
from python练习脚本.friends_ana import jiebaclearText, make_wordcloud, d
from pyecharts import Bar, Grid, Line
#机器人
def robots(name):
    my_friend = ensure_one(bot.search(name))
    # 调用图灵机器人API
    tuling = Tuling(api_key='254507344a264d67a9eaa68264e9e5d1')
    # 使用图灵机器人自动与指定好友聊天
    @bot.register(my_friend)
    def reply_my_friend(msg):
        tuling.do_reply(msg)
    embed()
# 向文件传输助手发送消息
def test(str):

    bot.file_helper.send(str)
def mesage():
    #获取好友列表(包括自己)
    my_friends = bot.friends(update=False)
    '''
    stats_text 函数:帮助我们简单统计微信好友基本信息
    简单的统计结果的文本
        :param total: 总体数量
        :param sex: 性别分布
        :param top_provinces: 省份分布
        :param top_cities: 城市分布
        :return: 统计结果文本
    '''
    print(my_friends.stats_text())
#折线图分析好友省份分布
def lines(attr,num):
    line = Line("Top 10 cities", title_top="50%")
    line.add(
    "人数最多",
    attr,
    num,
    mark_point=["max", "min"],
    legend_top="50%",
    )
    grid = Grid()
    grid.add(line, grid_top="60%")
    grid.render('H:grid.html')
#给指定朋友发送消息,图片
def sendtofriend(name):
    # 查找朋友
    my_friend = bot.friends().search(name)[0]
    # 发送消息
    my_friend.send('hello!')
    '''
    除此之外还有可以发送一下内容,自己动手尝试吧
    发送图片
    my_friend.send_image('hello.png')
    发送视频
    my_friend.send_video('hello.mp4')
    发送文件
    my_friend.send_file('hello.rar')
    '''
#微信城市分布条形图
def city(weight,city):
    mpl.rcParams['font.sans-serif'] = ['SimHei']
    n_groups = 10
    fig, ax = plt.subplots()
    index = np.arange(n_groups)
    bar_width = 0.35
    opacity = 0.4
    error_config = {'ecolor': '0.3'}
    rects1 = ax.bar(index, weight, bar_width,alpha=opacity, color='b', error_kw=error_config,label='城市')
    ax.set_xlabel('城市名称')
    ax.set_ylabel('数据占比(%)')
    ax.set_title('好友城市Top10')
    ax.set_xticks(index + bar_width / 2)
    ax.set_xticklabels((city))
    ax.legend()
    fig.tight_layout()
    plt.show()
# 定义个函数式用于分词
def jiebaclearText(text):
    # 定义一个空的列表,将去除的停用词的分词保存
    mywordList = []
    # 进行分词
    seg_list = jieba.cut(text, cut_all=False)
    # 将一个generator的内容用/连接
    listStr = '/'.join(seg_list)
    listStr = listStr.replace("class", "")
    listStr = listStr.replace("span", "")
    listStr = listStr.replace("emoji", "")
    # 打开停用词表
    f_stop = open(stopwords_path, encoding="utf8")
    # 读取
    try:
        f_stop_text = f_stop.read()
    finally:
        f_stop.close()  # 关闭资源
    # 将停用词格式化,用\n分开,返回一个列表
    f_stop_seg_list = f_stop_text.split("\n")
    # 对默认模式分词的进行遍历,去除停用词
    for myword in listStr.split('/'):
        # 去除停用词
        if not (myword.split()) in f_stop_seg_list and len(myword.strip()) > 1:
            mywordList.append(myword)
    return ' '.join(mywordList)

# 生成词云图
def make_wordcloud(text1, i):
    bg = plt.imread(d + r"/image/爱心01.jpg")
    # 生成
    wc = WordCloud(  # FFFAE3
        background_color="#FFFFFF",  # 设置背景为白色,默认为黑色
        width=990,  # 设置图片的宽度
        height=440,  # 设置图片的高度
        mask=bg,
        margin=10,  # 设置图片的边缘
        max_font_size=70,  # 显示的最大的字体大小
        random_state=20,  # 为每个单词返回一个PIL颜色
        font_path=d + '/static/simkai.ttf'  # 中文处理,用系统自带的字体
    ).generate(text1)
    # 为图片设置字体
    my_font = fm.FontProperties(fname=d + '/static/simkai.ttf')
    # 图片背景
    bg_color = ImageColorGenerator(bg)
    # 开始画图
    plt.imshow(wc.recolor(color_func=bg_color))
    # 为云图去掉坐标轴
    plt.axis("off")
    # 画云图,显示
    # 保存云图
    wc.to_file(d + r"/image/render_0%d.png" % i)
def wordcloud():
    # 清洗数据,生成词云图
    # 获取当前的项目文件加的路径
    d = path.dirname(__file__)

    # 微信昵称
    nick_name = ''
    #  微信个性签名
    wx_signature = ''
    for friend in my_friends:
        # 微信昵称:NickName
        nick_name = nick_name + friend.raw['NickName']
        # 个性签名:Signature
        wx_signature = wx_signature + friend.raw['Signature']

    nick_name = jiebaclearText(nick_name)
    wx_signature = jiebaclearText(wx_signature)
    make_wordcloud(nick_name, 1)
    make_wordcloud(wx_signature, 2)
    # 获取微信公众号名称
    wx_public_name = ''
    # # 公众号简介
    wx_pn_signature = ''
    # 获取微信公众号列表
    my_wx_pn = bot.mps(update=False)
    for wx_pn in my_wx_pn:
        wx_public_name = wx_public_name + wx_pn.raw['NickName']
        wx_pn_signature = wx_pn_signature + wx_pn.raw['Signature']

    wx_public_name = jiebaclearText(wx_public_name)
    make_wordcloud(wx_public_name, 3)
    wx_pn_signature = jiebaclearText(wx_pn_signature)
    make_wordcloud(wx_pn_signature, 4)
if __name__=='__main__':

    bot = Bot(cache_path="H:wxpy.pkl")
    # 获取好友列表(包括自己)
    my_friends = bot.friends(update=False)
    # 读取停用词表
    stopwords_path = d + '/static/stopwords.txt'
    wordcloud()
    #robots('姓名')
    #test('hello')
    # 城市分布数量权值
    # city_weight = (10.2, 8.98, 8.57, 2.04, 2.04, 1.63, 1.63, 1.22, 1.22, 1.22)
    # city=('荆州', '武汉', '黄石', '海淀', '广州','深圳', '黄冈', '杭州', '长沙', '昌平')
    # city(city_weight,city)
    mesage()

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值