当前位置: 移动技术网 > IT编程>脚本编程>Python > 使用 python 进行微信好友分析

使用 python 进行微信好友分析

2019年06月03日  | 移动技术网IT编程  | 我要评论

小型飞机陕西坠毁,喝茶的好处和坏处,厂家授权书

使用 python 进行微信好友分析

1. 使用到的库

① wxpy:初始化微信机器人

② openpyxl:保存微信好友数据为excel表格

③ pyecharts:生成可视化的地图

④ wordcloud、matplotlib、jieba:生成词云图

特别提醒】:pyecharts 库用的是0.5.x版本,而在 pip 中安装的为1.x.x版本,因此需要自行到【】中下载。

2. 基本功能

① 分析微信好友数据

② 生成词云图

③ 生成地图展示

3. 代码实现

此处使用来实现

(1) 导入模块

1 #  导入模块
2 from wxpy import bot
3 import openpyxl
4 from pyecharts import map
5 from wordcloud import wordcloud
6 import matplotlib.pyplot as plt
7 import jieba

 

(2) 初始化机器人和获取微信好友的源信息

此处调用 bot() 方法,需要扫码登陆微信网页版,后续操作才能进行。

 1 def __init__(self, toexcelfile="", tocityfile="", tomapprovincefile="", tomapcityfile=""):
 2     ''' 初始化机器人和其他参数 '''
 3     # 初始化机器人,需要扫码
 4     self.bot = bot()
 5     # 获取我所有的微信好友信息 - 存储基础信息(未处理)
 6     self.allfriends_info = self.bot.friends()
 7     # 我的微信好友个数
 8     self.allfriends_num = len(self.allfriends_info)
 9     # 保存微信好友信息的表格文件路径(.xlsx)
10     self.excelfile = toexcelfile
11     # 保存城市词云图的文件路径(.png/.jpg)
12     self.wcofcityfile = tocityfile
13     # 保存省份地图的文件路径(.html)
14     self.mapprovincefile = tomapprovincefile
15     # 其他可用参数
16     self.mapcityfile = tomapcityfile
17     # 自动调用run方法,使得在实例化对象后自动运行其他函数
18     self.run()

 

(3) 统计和处理微信好友的信息

除了列出的还有 个性签名头像其他属性。

 1 def getfriendsinfo(self):
 2     ''' 获取微信好友的全部信息 '''
 3     # 存储微信好友的信息(经过信息处理的)
 4     self.friendsinfo = []
 5     # 定义列标题
 6     self.infotitle = ['nickname', 'remarkname', 'sex', 'province', 'city']
 7     for afriend in self.allfriends_info:
 8         # 获取昵称
 9         nickname = afriend.raw.get(self.infotitle[0], none)
10         # 获取备注
11         remarkname = afriend.raw.get(self.infotitle[1], none)
12         # 获取性别
13         sex = {1:"男", 2:"女", 0:"其他"}.get(afriend.raw.get(self.infotitle[2], none), none)
14         # 获取省份
15         province = afriend.raw.get(self.infotitle[3], none)
16         # 获取城市
17         city = afriend.raw.get(self.infotitle[4], none)
18         listmp = [nickname, remarkname, sex, province, city]
19         self.friendsinfo.append(listmp)

 

(4) 保存微信好友的信息

在这保存为excel表格,在代码中插入表头行,为了便于阅读。

 1 def savefriendsinfoasexcel(self, excelname):
 2     ''' 保存微信好友的信息到 excel 表格中 '''
 3     # 生成openpyxl对象
 4     workbook = openpyxl.workbook()
 5     # 激活表格
 6     sheet = workbook.active
 7     # 设置表格标题
 8     sheet.title = 'wechatfriendsinfo'
 9     # 填充列标题到第一行
10     for _ in range(len(self.infotitle)):
11         sheet.cell(row=1, column=_+1, value=self.infotitle[_])
12     # 填充微信好友信息,从第二行开始
13     for i in range(self.allfriends_num):
14         for j in range(len(self.infotitle)):
15             sheet.cell(row=i+2, column=j+1, value=str(self.friendsinfo[i][j]))
16     # 若文件名非空,则保存到该路径下
17     if excelname != "":
18         workbook.save(excelname)
19         print(">>> save wechat friends' information successfully!")

 

(5) 分析微信好友的信息

1 def quiteanalyzefriendsinfo(self):
2     ''' 分析数据,一步到位,直接了当 '''
3     print(self.allfriends_info.stats_text())

 

(6) 生成city词云图

 1 def creatwordcloudofcity(self, cityname):
 2     ''' 使用获取的数据生成city词云图 '''
 3     # 获取所有的城市
 4     citystr = ""
 5     for i in range(self.allfriends_num):
 6         if self.friendsinfo[i][4] not in citystr:
 7             citystr += " " + self.friendsinfo[i][4]
 8     #jieba库精确模式分词
 9     wordlist = jieba.lcut(citystr)
10     citystr = ' '.join(wordlist)
11     # 加载背景图片
12     #cloud_mask = np.array(image.open(backgroundfile))
13     #设置词云图属性
14     font = r'c:\windows\fonts\simfang.ttf' # 设置字体路径
15     wc = wordcloud(
16         background_color = 'black',     # 背景颜色
17         #mask = cloud_mask,             # 背景图片
18         max_words = 100,                # 设置最大显示的词云数
19         font_path = font,               # 设置字体形式(在本机系统中)
20         height = 300,                   # 图片高度
21         width = 600,                    # 图片宽度
22         max_font_size = 100,            # 字体最大值
23         random_state = 100,             # 配色方案的种类
24         )
25     # 生成词云图
26     myword = wc.generate(citystr)
27     #展示词云图
28     plt.imshow(myword)
29     plt.axis('off')
30     plt.show()
31     # 若文件名非空,则保存到该路径下
32     if cityname != "":
33         #保存词云图
34         wc.to_file(cityname)
35         print(">>> creat wechat wordcloud of city successfully!")

 

(7) 生成province地图

 1 def creatmapprovince(self, mapfile):
 2     ''' 使用获取的数据生成province地图 '''
 3     # 获取所有省份
 4     provincelist, provincenum = [], []
 5     for i in range(self.allfriends_num):
 6         if self.friendsinfo[i][3] not in provincelist:
 7             provincelist.append(self.friendsinfo[i][3])
 8             provincenum.append(0)
 9     for i in range(self.allfriends_num):
10         for j in range(len(provincelist)):
11             if self.friendsinfo[i][3] == provincelist[j]:
12                 provincenum[j] += 1
13     # 生成 map
14     map = map("各省微信好友分布", width=1000, height=800)
15     map.add("", provincelist, provincenum, maptype="china", is_visualmap=true, visual_text_color='#000')
16     # 若文件名非空,则保存到该路径下
17     if mapfile != "":
18         map.render(mapfile)
19         print(">>> creat wechat map of provinces seccessfully!")

 

(8) 生成city地图

 1 def creatmapcity(self, mapfile):
 2         ''' 使用获取的数据生成city地图 '''
 3         # 获取所有省份
 4         citylist, citynum = [], []
 5         for i in range(self.allfriends_num):
 6             if self.friendsinfo[i][4] not in citylist:
 7                 citylist.append(self.friendsinfo[i][4])
 8                 citynum.append(0)
 9         for i in range(self.allfriends_num):
10             for j in range(len(citylist)):
11                 if self.friendsinfo[i][4] == citylist[j]:
12                     citynum[j] += 1
13         for i in range(len(citylist)):
14             citylist[i] += '市'
15         # 生成 map
16         map = map("各市微信好友分布", width=1000, height=800)
17         map.add("", citylist, citynum, maptype="广东", is_visualmap=true, visual_text_color='#000')
18         # 若文件名非空,则保存到该路径下
19         if mapfile != "":
20             map.render(mapfile)
21             print(">>> creat wechat map of cities seccessfully!")

有了上述实现各个功能的方法,那么就差一个调用各种方法的方法了。

(9) run方法

 1 def run(self):
 2     # 获取微信好友信息
 3     self.getfriendsinfo()
 4     print(">>> get wechat friends' information successfully!")
 5     print(">>> members:", self.allfriends_num)
 6     # 保存微信好友信息
 7     self.savefriendsinfoasexcel(self.excelfile)
 8     # 分析微信好友信息
 9     self.quiteanalyzefriendsinfo()
10     # 使用微信好友的 city 产生词云图
11     self.creatwordcloudofcity(self.wcofcityfile)
12     # 生成微信好友的 province 地图
13     self.creatmapprovince(self.mapprovincefile)
14     # 生成微信好友的 city 地图
15     self.creatmapcity(self.mapcityfile)

对于文件路径,在main函数中传递即可。【注】:上述代码都在类中,在此处结束,下面为main函数

1 if __name__ == "__main__":
2     toexcelfile = "./wechatanalyze//friendsinfo.xlsx"      # 微信好友信息的excel表格保存路径
3     topicturefile = "./wechatanalyze//citywordcloud.png"   # 微信好友信息city词云图保存路径
4     tomapfileprovince = "./wechatanalyze//wechatprovincemap.html" # 微信好友信息province地图保存路径
5     tomapfilecity = "./wechatanalyze//wechatcitymap.html"  # 微信好友信息city地图保存路径
6     # wechatrobot对象实例化
7     robot = wechatrobot(toexcelfile, topicturefile, tomapfileprovince, tomapfilecity)

是不是觉得main函数很简短,哈哈,没错,就是这么简!

接下来看看实现的效果吧!

>>> 这个是终端显示效果

>>> 这个是保存为excel表格的内容

 >>> 这个是微信好友各省的分布

>>> 这个是微信好友各市的分布

 

ok. 今天就分享到这啦!最后附上完整代码!

 

参考文献:

① 用python玩微信:

② pyecharts 中部分import 不到:

③ pyecharts 中地图显示不全:

 

  1 # -*- coding: utf-8 -*-
  2 '''
  3 this is a program which can analyze datas of wechat friends.
  4 @author: bpf
  5 '''
  6 
  7 #  导入模块
  8 from wxpy import bot
  9 import openpyxl
 10 from pyecharts import map
 11 from wordcloud import wordcloud
 12 import matplotlib.pyplot as plt
 13 import jieba
 14 
 15 class wechatrobot:
 16 
 17     '''====================== 1. 获取微信好友信息 ======================'''
 18     def __init__(self, toexcelfile="", tocityfile="", tomapprovincefile="", tomapcityfile=""):
 19         ''' 初始化机器人和其他参数 '''
 20         # 初始化机器人,需要扫码
 21         self.bot = bot()
 22         # 获取我所有的微信好友信息 - 存储基础信息(未处理)
 23         self.allfriends_info = self.bot.friends()
 24         # 我的微信好友个数
 25         self.allfriends_num = len(self.allfriends_info)
 26         # 保存微信好友信息的表格文件路径(.xlsx)
 27         self.excelfile = toexcelfile
 28         # 保存城市词云图的文件路径(.png/.jpg)
 29         self.wcofcityfile = tocityfile
 30         # 保存省份地图的文件路径(.html)
 31         self.mapprovincefile = tomapprovincefile
 32         # 其他可用参数
 33         self.mapcityfile = tomapcityfile
 34         # 自动调用run方法,使得在实例化对象后自动运行其他函数
 35         self.run()
 36 
 37     '''====================== 2. 统计微信好友信息 ======================'''
 38     def getfriendsinfo(self):
 39         ''' 获取微信好友的全部信息 '''
 40         # 存储微信好友的信息(经过信息处理的)
 41         self.friendsinfo = []
 42         # 定义列标题
 43         self.infotitle = ['nickname', 'remarkname', 'sex', 'province', 'city']
 44         for afriend in self.allfriends_info:
 45             # 获取昵称
 46             nickname = afriend.raw.get(self.infotitle[0], none)
 47             # 获取备注
 48             remarkname = afriend.raw.get(self.infotitle[1], none)
 49             # 获取性别
 50             sex = {1:"男", 2:"女", 0:"其他"}.get(afriend.raw.get(self.infotitle[2], none), none)
 51             # 获取省份
 52             province = afriend.raw.get(self.infotitle[3], none)
 53             # 获取城市
 54             city = afriend.raw.get(self.infotitle[4], none)
 55             listmp = [nickname, remarkname, sex, province, city]
 56             self.friendsinfo.append(listmp)
 57     
 58     '''====================== 3. 保存微信好友信息 ======================'''
 59     def savefriendsinfoasexcel(self, excelname):
 60         ''' 保存微信好友的信息到 excel 表格中 '''
 61         # 生成openpyxl对象
 62         workbook = openpyxl.workbook()
 63         # 激活表格
 64         sheet = workbook.active
 65         # 设置表格标题
 66         sheet.title = 'wechatfriendsinfo'
 67         # 填充列标题到第一行
 68         for _ in range(len(self.infotitle)):
 69             sheet.cell(row=1, column=_+1, value=self.infotitle[_])
 70         # 填充微信好友信息,从第二行开始
 71         for i in range(self.allfriends_num):
 72             for j in range(len(self.infotitle)):
 73                 sheet.cell(row=i+2, column=j+1, value=str(self.friendsinfo[i][j]))
 74         # 若文件名非空,则保存到该路径下
 75         if excelname != "":
 76             workbook.save(excelname)
 77             print(">>> save wechat friends' information successfully!")
 78 
 79     '''====================== 4. 分析微信好友信息 ======================'''
 80     def quiteanalyzefriendsinfo(self):
 81         ''' 分析数据,一步到位,直接了当 '''
 82         print(self.allfriends_info.stats_text())
 83     
 84     '''====================== 5. 产生city词云图 ======================'''
 85     def creatwordcloudofcity(self, cityname):
 86         ''' 使用获取的数据生成city词云图 '''
 87         # 获取所有的城市
 88         citystr = ""
 89         for i in range(self.allfriends_num):
 90             if self.friendsinfo[i][4] not in citystr:
 91                 citystr += " " + self.friendsinfo[i][4]
 92         #jieba库精确模式分词
 93         wordlist = jieba.lcut(citystr)
 94         citystr = ' '.join(wordlist)
 95         # 加载背景图片
 96         #cloud_mask = np.array(image.open(backgroundfile))
 97         #设置词云图属性
 98         font = r'c:\windows\fonts\simfang.ttf' # 设置字体路径
 99         wc = wordcloud(
100             background_color = 'black',     # 背景颜色
101             #mask = cloud_mask,             # 背景图片
102             max_words = 100,                # 设置最大显示的词云数
103             font_path = font,               # 设置字体形式(在本机系统中)
104             height = 300,                   # 图片高度
105             width = 600,                    # 图片宽度
106             max_font_size = 100,            # 字体最大值
107             random_state = 100,             # 配色方案的种类
108             )
109         # 生成词云图
110         myword = wc.generate(citystr)
111         #展示词云图
112         plt.imshow(myword)
113         plt.axis('off')
114         plt.show()
115         # 若文件名非空,则保存到该路径下
116         if cityname != "":
117             #保存词云图
118             wc.to_file(cityname)
119             print(">>> creat wechat wordcloud of city successfully!")
120     
121     '''===================== 6. 产生province地图 ====================='''
122     def creatmapprovince(self, mapfile):
123         ''' 使用获取的数据生成province地图 '''
124         # 获取所有省份
125         provincelist, provincenum = [], []
126         for i in range(self.allfriends_num):
127             if self.friendsinfo[i][3] not in provincelist:
128                 provincelist.append(self.friendsinfo[i][3])
129                 provincenum.append(0)
130         for i in range(self.allfriends_num):
131             for j in range(len(provincelist)):
132                 if self.friendsinfo[i][3] == provincelist[j]:
133                     provincenum[j] += 1
134         # 生成 map
135         map = map("各省微信好友分布", width=1000, height=800)
136         map.add("", provincelist, provincenum, maptype="china", is_visualmap=true, visual_text_color='#000')
137         # 若文件名非空,则保存到该路径下
138         if mapfile != "":
139             #map.show_config()
140             map.render(mapfile)
141             print(">>> creat wechat map of provinces seccessfully!")
142     
143     '''===================== 7. 产生city地图 ====================='''
144     def creatmapcity(self, mapfile):
145         ''' 使用获取的数据生成city地图 '''
146         # 获取所有省份
147         citylist, citynum = [], []
148         for i in range(self.allfriends_num):
149             if self.friendsinfo[i][4] not in citylist:
150                 citylist.append(self.friendsinfo[i][4])
151                 citynum.append(0)
152         for i in range(self.allfriends_num):
153             for j in range(len(citylist)):
154                 if self.friendsinfo[i][4] == citylist[j]:
155                     citynum[j] += 1
156         for i in range(len(citylist)):
157             citylist[i] += '市'
158         # 生成 map
159         map = map("各市微信好友分布", width=1000, height=800)
160         map.add("", citylist, citynum, maptype="广东", is_visualmap=true, visual_text_color='#000')
161         # 若文件名非空,则保存到该路径下
162         if mapfile != "":
163             map.render(mapfile)
164             print(">>> creat wechat map of cities seccessfully!")
165         
166     '''===================== 8. 自动执行函数 ====================='''
167     def run(self):
168         # 获取微信好友信息
169         self.getfriendsinfo()
170         print(">>> get wechat friends' information successfully!")
171         print(">>> members:", self.allfriends_num)
172         # 保存微信好友信息
173         self.savefriendsinfoasexcel(self.excelfile)
174         # 分析微信好友信息
175         self.quiteanalyzefriendsinfo()
176         # 使用微信好友的 city 产生词云图
177         self.creatwordcloudofcity(self.wcofcityfile)
178         # 生成微信好友的 province 地图
179         self.creatmapprovince(self.mapprovincefile)
180         # 生成微信好友的 city 地图
181         self.creatmapcity(self.mapcityfile)
182         
183 if __name__ == "__main__":
184     toexcelfile = "./wechatanalyze//friendsinfo.xlsx"      # 微信好友信息的excel表格保存路径
185     topicturefile = "./wechatanalyze//citywordcloud.png"   # 微信好友信息city词云图保存路径
186     tomapfileprovince = "./wechatanalyze//wechatprovincemap.html" # 微信好友信息province地图保存路径
187     tomapfilecity = "./wechatanalyze//wechatcitymap.html"  # 微信好友信息city地图保存路径
188     # wechatrobot对象实例化
189     robot = wechatrobot(toexcelfile, topicturefile, tomapfileprovince, tomapfilecity)

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网