微信好友分布分析

一.环境要求

Windows 10;python 3.7;

第三方库

wxpy 0.3.9.8——登录微信
openpyxl 2.6.2——可对 excel 表格进行操作

pyecharts 0.5.11——百度的开源可视化库,

wordcloud 1.5.0——词云制作库

matplotlib 3.1.0——生成词云图

pandas 0.24.2——读取 excel 表格的数据

pyecharts-snapshot 0.2.0——是 pyecharts 的依赖库之一

echarts-countries-pypkg——pyecharts 的世界地图包

echarts-china-provinces-pypkg——pyecharts 的中国省份地图包

第三方库的安装

(2019年6月10号)除了 pyecharts 其它都可以直接使用 pip 安装,而安装 pycharts 需要特殊些(因为最新版已出为 1.X版,不向下兼容),如下:

pip install wxpy
pip install openpyxl
pip install PIL
pip install pandas
pip install wordcloud

pip install pyecharts==0.5.11
pip install echarts-countries-pypkg
pip install echarts-china-provinces-pypkg
pip install pyecharts-snapshot

  

二.分析思路

1.登录微信,获取好友的基本信息

使用 wxpy 的 Bot() 模块,登录微信

from wxpy import *

bot = Bot(cache_path = True)

#获取全部好友的信息
friend_all = bot.friends()

#输出 friend_all 看一下
print(friend_all)

#输出好友数量#print(len(friend_all))

输出结果为

2.把好友信息存为更易处理的二维列表

#建立一个二维列表,存储基本好友信息
lis = [[‘NickName‘,‘Sex‘,‘City‘,‘Province‘,‘Signature‘,‘HeadImgUrl‘,‘HeadImgFlag‘]]
#把好有特征数据保存为列表
for a_friend in friend_all:
    #遍历 friend_all, 并使用 raw.get(‘ ‘, None), 来获取每一各朋友的基本信息
    NickName = a_friend.raw.get(‘NickName‘, None)
    Sex = {1:"男", 2:"女", 0:"其它"}.get(a_friend.raw.get(‘Sex‘, None), None)
    City = a_friend.raw.get(‘City‘, None)
    Province = a_friend.raw.get(‘Province‘, None)
    Signature = a_friend.raw.get(‘Signature‘, None)
    HeadImgUrl = a_friend.raw.get(‘HeadImgUrl‘, None)
    HeadImgFlag = a_friend.raw.get(‘HeadImgFlag‘, None)
    list_0 = [NickName, Sex, City, Province, Signature, HeadImgUrl, HeadImgFlag]
    lis.append(list_0)

输出 lis

3.把列表存为 excel 表格,方便本地查看

#把列表转换为 xlsx 表格
def list_to_xlsx(filename, list):

    import openpyxl  #新建一个表格
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.title = ‘Friends‘
    file_name = filename + ‘.xlsx‘
    for i in range(0, len(list)):
        for j in range(0, len(list[i])):
            sheet.cell(row = i+1, column = j+1, value = str(list[i][j]))

    wb.save(file_name)
    print("读写数据成功")

#把列表生成表格
list_to_xlsx(‘wechat_friend‘, lis)

生成的表格为

4.对 execl 表格进行处理,利用表格信息生成词云

from wordcloud import WordCloud
import matplotlib.pyplot as plt
import pandas as pd
from pandas import read_excel

df = read_excel(‘wechat_friend.xlsx‘)

#使用 WordCloud 生成词云
word_list = df[‘City‘].fillna(‘‘).tolist()
new_text = ‘ ‘.join(word_list)
wordcloud = WordCloud(font_path=‘msyh.ttc‘, background_color = ‘white‘).generate(new_text)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
plt.savefig("WordCloud.png")
print("保存词云图")

词云图展示

5.利用表格信息生成网页词云图(即HTML)

#使用 pyecharts 生成词云
from pyecharts import WordCloud

city_list = df[‘City‘].fillna(‘‘).tolist()
count_city = pd.value_counts(city_list)
name = count_city.index.tolist()
value = count_city.tolist()

wordcloud = WordCloud(width=1300,height=620)
wordcloud.add("",name,value,word_size_range=[20,100])
#wordcloud.show_config()
#wordcloud.render(r‘D:\wc.html‘)
wordcloud.render(‘wordcloud.html‘)
print("网页词云图已生成")

词云图展示

6.利用表格信息生成好友地图分布图

#将好友展示在地图上
from pyecharts import Map

province_list = df[‘Province‘].fillna(‘‘).tolist()
count_province = pd.value_counts(province_list)
attr = count_province.index.tolist()
value1 = count_province.tolist()
map = Map("各省微信好友分布", width=1200,height=600)
map.add("",attr, value1, maptype=‘china‘,is_visualmap=True,visualmap_text_color=‘#000‘,is_label_show=True)
#map.show_config()
map.render(‘map.html‘)
print("map已生成")

微信好友分布图展示

三.最后代码汇总

把上面的代码,规范一下,可得——

# -*- coding: utf-8 -*-
"""
Created on Mon Jun  3 10:01:35 2019

@author: haiwe
"""
#获取微信接口
from wxpy import *

#把获取的微信好友信息存为列表
def wx_friend_information(friend_all):

    #先生成一个二维列表,用来储存好友信息
    lis = [[‘NickName‘,‘Sex‘,‘City‘,‘Province‘,‘Signature‘,‘HeadImgUrl‘,‘HeadImgFlag‘]]
    #遍历 friend_all, 并使用 raw.get(‘ ‘, None), 来获取每一各朋友的基本信息
    for a_friend in friend_all:
        NickName = a_friend.raw.get(‘NickName‘, None)
        Sex = {1:"男", 2:"女", 0:"其它"}.get(a_friend.raw.get(‘Sex‘, None), None)
        City = a_friend.raw.get(‘City‘, None)
        Province = a_friend.raw.get(‘Province‘, None)
        Signature = a_friend.raw.get(‘Signature‘, None)
        HeadImgUrl = a_friend.raw.get(‘HeadImgUrl‘, None)
        HeadImgFlag = a_friend.raw.get(‘HeadImgFlag‘, None)
        list_0 = [NickName, Sex, City, Province, Signature, HeadImgUrl, HeadImgFlag]
        lis.append(list_0)

    return lis

#把列表转换为 xlsx 表格,并保存表格
def list_to_xlsx(filename, list):

    #使用 openpyxl 创建空表格
    import openpyxl
    wb = openpyxl.Workbook()
    #获得当前正在显示的 sheet, 或 wb.get_active_sheet()
    sheet = wb.active
    #表格的 sheet 页命名为 Friends
    sheet.title = ‘Friends‘
    # execl 文件命名
    file_name = filename + ‘.xlsx‘
    #遍历 excel 表格,并读入数据
    for i in range(0, len(list)):
        for j in range(0, len(list[i])):
            #为什么 i+1,j+1 不懂
            sheet.cell(row = i+1, column = j+1, value = str(list[i][j]))
    #保存表格
    wb.save(file_name)
    print("读写数据成功")

from wordcloud import WordCloud
import matplotlib.pyplot as plt
import pandas as pd
#使用 pandas 的 read_excel 模块读取execl 表格
from pandas import read_excel
#import numpy as np

#生成词云图
def create_wordcloud(df):

    #把 df(dataframe) 中城市那列中 为空的 替换为 空字符,并把替换后的城市列存在 city_list中
    word_list = df[‘City‘].fillna(‘‘).tolist()
    #把 city_list 列表中的 各项 用空格隔开,并变为字符串
    new_text = ‘ ‘.join(word_list)
    #设置词云图的字体为 ‘msyh.ttc‘, 背景为白色(默认为黑色),并用 generate() 生成词云图
    wordcloud = WordCloud(font_path=‘msyh.ttc‘, background_color = ‘white‘).generate(new_text)
    #展示生成的词云图
    plt.imshow(wordcloud)
    #plt.axis("off")
    #plt.show()
    plt.savefig("WordCloud.png")
    print("保存词云图")

#使用 pyecharts 生成词云
def create_wordcloud_html(df):

    #调用 pyecharts 中 wordcloud 模块
    from pyecharts import WordCloud

    #把 df(dataframe) 中城市那列中 为空的 替换为 空字符,并把替换后的城市列存在 city_list中
    city_list = df[‘City‘].fillna(‘‘).tolist()

    #使用 pandas.value_count() 返回 city_list 中各项和其对应的频数(两者一一对应),并存在 count_city 中
    count_city = pd.value_counts(city_list)
    #把 count_city 中的项提取出来,并存在 name 中
    name = count_city.index.tolist()
    #把 count_city 中的频数提取出来
    value = count_city.tolist()
    #生成词云图
    wordcloud = WordCloud(width=1300,height=620)
    #往词云图中添加信息,
    wordcloud.add("",name,value,word_size_range=[20,100])
    #输出词云图的配置
    #wordcloud.show_config()
    #wordcloud.render(r‘D:\wc.html‘)
    #保存词云图
    wordcloud.render(‘wordcloud.html‘)
    print("网页词云图已生成")

#将好友展示在地图上
def create_map(df):

    #使用 pyechart 的 Map 模块,生成网页词云图
    from pyecharts import Map

    #把 df(dataframe) 中省份那列中 为空的 替换为 空字符,并把替换后的城市列存在 province_list中
    province_list = df[‘Province‘].fillna(‘‘).tolist()
    #使用 pandas.value_count() 返回 province_list 中各项和其对应的频数(两者一一对应),并存在 count_province 中
    count_province = pd.value_counts(province_list)
    #把 count_province 中的项提取出来,并存在 name 中
    attr = count_province.index.tolist()
    #把 count_province 中的频数提取出来
    value1 = count_province.tolist()
    #生成一个标题为 “ ”的空白 HTML
    map = Map("各省微信好友分布", width=1200,height=600)
    #向空白 HTML 中添加 信息,设置地图为 中国地图,并显示地图,设置地图上文字颜色,并显示标签
    map.add("",attr, value1, maptype=‘china‘,is_visualmap=True,visualmap_text_color=‘#000‘,is_label_show=True)
    #map.show_config()
    #保存词云网页
    map.render(‘map.html‘)
    print("map已生成")

if __name__ == "__main__":

    #获取登录二维码
    bot = Bot(cache_path = True)

    #获取微信朋友的基本数据
    friend_all = bot.friends()
    list = wx_friend_information(friend_all)
    list_to_xlsx(‘wechat_friend‘, list)

    df = read_excel(‘wechat_friend.xlsx‘)
    create_wordcloud(df)
    create_wordcloud_html(df)
    create_map(df)

原文地址:https://www.cnblogs.com/justlikecode/p/10966625.html

时间: 2024-08-29 22:10:30

微信好友分布分析的相关文章

使用 python 进行微信好友分析

使用 python 进行微信好友分析 1. 使用到的库 ① wxpy:初始化微信机器人 ② openpyxl:保存微信好友数据为Excel表格 ③ pyecharts:生成可视化的地图 ④ wordcloud.matplotlib.jieba:生成词云图 [特别提醒]:pyecharts 库用的是0.5.x版本,而在 pip 中安装的为1.x.x版本,因此需要自行到[官网]中下载. 2. 基本功能 ① 分析微信好友数据 ② 生成词云图 ③ 生成地图展示 3. 代码实现 此处使用类来实现 (1)

微信好友大揭秘,使用Python抓取朋友圈数据,通过人脸识别全面分析好友,一起看透你的“朋友圈”

微信:一个提供即时通讯服务的应用程序,更是一种生活方式,超过数十亿的使用者,越来越多的人选择使用它来沟通交流. 不知从何时起,我们的生活离不开微信,每天睁开眼的第一件事就是打开微信,关注着朋友圈里好友的动态,而朋友圈中或虚或实的状态更新,似乎都在证明自己的"有趣",寻找那份或有或无的存在感. 有人选择在朋友圈记录生活的点滴,有人选择在朋友圈展示自己的观点.有时我们想去展示自己,有时又想去窥探着别人的生活,而有时又不想别人过多的了解自己的生活,或是屏蔽对方,或是不给对方看朋友圈,又或是不

初出茅庐-----微信好友分析与微信机器人

初出茅庐-----微信好友分析与微信机器人 一.微信好友分析 1.简介 对微信的好友进行分析,统计好友的人数,省市的分布,并排序,并统计好友签名用词的特点.用pyechart图像显示,并存为网页文件. 2.函数描述 函数 描述 get_friends_info(self) 获取好像信息,返回lis列表 friends_info_lis_to_excle(self) 把lis信息写入到excle extract_data_as_two_lis(self, condition) 参数为conditi

练习:微信好友分析

来源:http://www.cnblogs.com/jiaoyu121/p/6944398.html 1.好友性别分布 import itchat itchat.login() #itchat.send(u'你好','filehelper') friends = itchat.get_friends(update=True)[0:] #print len(friends) male = female = other = 0 for i in friends[1:]: sex = i['Sex']

利用Python网络爬虫抓取微信好友的所在省位和城市分布及其可视化

前几天给大家分享了如何利用Python网络爬虫抓取微信好友数量以及微信好友的男女比例,感兴趣的小伙伴可以点击链接进行查看.今天小编给大家介绍如何利用Python网络爬虫抓取微信好友的省位和城市,并且将其进行可视化,具体的教程如下. 爬取微信好友信息,不得不提及这个itchat库,简直太神奇了,通过它访问微信好友基本信息可谓如鱼得水.下面的代码是获取微信好友的省位信息: 程序运行之后,需要扫描进行授权登录,之后在Pycharm的控制台上会出现如下图的红色提示,这些红色的字体并不是我们通常遇到的Py

分析微信好友列表信息(json)

在前面我们玩了好多静态的 HTML,但还有一些常见的动态数据,比如,商品的评论数据.实时的直播弹幕等,这些数据是会经常发生改变的,所以很多网站就会用到 Json 来传输这些数据. Python JSON 可以用 json 模块, 1. 将 python 对象转化为 json是这样的 json.dumps() 2. 将json数据转化为python对象是这样的 json.loads() 微信好友列表 登陆微信网页版(据说现在很多微信号不能等网页版了??) 很容易找到有一个请求,会返回所有好友的信息

python 实现微信自动回复和好友签名分析

废话不多说了,代码不多,简单粗暴,我就直接上代码: 1.自动回复 #coding=utf8 import itchat import time # 自动回复 # 封装好的装饰器,当接收到的消息是Text,即文字消息 @itchat.msg_register('Text') def text_reply(msg): # 当消息不是由自己发出的时候 if not msg['FromUserName'] == myUserName: # 发送一条提示给文件助手 itchat.send_msg(u"[%

我的第一个微信好友数据分析

本次我们利用python来分析一下我们微信的好友数据 首先安装7个依赖库 1.Pillow PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了.PIL功能非常强大,但API却非常简单易用. 由于PIL仅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基础上创建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了许多新特性,因此,我们可以直接安装使用Pillow,如果有annaconda,则直接使用即可,如无,

ListView模拟微信好友功能

ListView模拟微信好友功能 效果图: 分析: 1.创建listView 2.创建数据 3.创建适配器 将数据放到呈现数据的容器里面. 将这个容器(带数据)连接适配器. 4.ListView设置适配器 代码: 1 package fry; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import com.example.weChatFriends.R; 7 8 import android.app.Activity