码迷,mamicode.com
首页 > 微信 > 详细

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

时间:2019-06-06 09:28:48      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:列表   imp   lambda   展示   top   键值   col   charts   option   

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

一、微信好友分析

1.简介

对微信的好友进行分析,统计好友的人数,省市的分布,并排序,并统计好友签名用词的特点。用pyechart图像显示,并存为网页文件。

2.函数描述

 

函数 描述
get_friends_info(self) 获取好像信息,返回lis列表
friends_info_lis_to_excle(self) 把lis信息写入到excle
extract_data_as_two_lis(self, condition) 参数为condition 词频,提取两个列表,condition 和 人数,降序列表
city_wordcloud(self, save_name, condition) 参数为 save_name 自动添加jpg 创建X条件词云
 pillar_picture(self, condition, render_name) 参数为condition ,创建柱形html图片
map_picture(self, condition, picture_name, keylist, valueslist, Map_condition) 参数为condition,picture_name, keylist, valueslist, Map_condition->china或者广东创建html地图图片,图片名字为picture_name
map_visualmap() -> Map 创建地图
find_friends_in_condition(self, condition) 参数为condition,返回一个二维列表

3.代码实现

  1 from wxpy import *
  2 from wordcloud import WordCloud
  3 import numpy as np
  4 from PIL import Image
  5 import matplotlib.pyplot as plt
  6 from pandas import read_excel
  7 import pandas as pd
  8 
  9 class  wechat_test():
 10 
 11     def __init__(self, filename, sheetname):
 12         self.filename = filename
 13         self.sheetname = sheetname
 14 
 15     def get_friends_info(self): #获取好像信息,返回lis列表
 16         bot = Bot()
 17         lis = [[name, real_name, sex, city, province]]  # 把信息存储为一个二维列表,添加头部信息
 18         friend_all = bot.friends()
 19 
 20         for a_friend in friend_all:
 21             NickName = a_friend.raw.get(NickName, None) #获取所有好友信息 raw表示获取全部信息
 22             RemarkName = a_friend.raw.get(RemarkName, None)
 23             Sex = {1: "", 2: "", 0: "其他"}.get(a_friend.raw.get(Sex, None), None)
 24             City = a_friend.raw.get(City, None)
 25             Province = a_friend.raw.get(Province, None)
 26             Signature = a_friend.raw.get(Signature, None)
 27             #HeadImgUrl = a_friend.raw.get(‘HeadImgUrl‘, None)
 28             #HeadImgFlag = a_friend.raw.get(‘HeadImgFlag‘, None)
 29             list_0 = [NickName, RemarkName, Sex, City, Province, Signature]
 30             lis.append(list_0)
 31         return lis
 32 
 33     # 把lis信息写入到excle
 34     def friends_info_lis_to_excle(self):
 35         import openpyxl
 36         lis = self.get_friends_info()
 37         wb = openpyxl.Workbook()
 38         sheet = wb.active
 39         sheet.title = self.sheetname
 40         for i in range(0, len(lis)):
 41             for j in range(0, len(lis[i])):
 42                 sheet.cell(row=i+1, column=j+1, value=str(lis[i][j]))
 43         wb.save(self.filename)
 44         print("excel保存成功")
 45 
 46     #参数为condition 词频,提取两个列表,condition 和 人数,降序列表
 47     def extract_data_as_two_lis(self, condition):
 48         df = read_excel(self.filename, sheet_name=self.sheetname)
 49         X_list = df[condition].fillna(0).tolist()  # 把列转换为list,用0替换Nan?
 50         counts = {}  # 创建字典
 51         for word in X_list:
 52             counts[word] = counts.get(word, 0) + 1  # 统计词频
 53         items = list(counts.items())  # 返回所有键值对
 54         items.sort(key=lambda x: x[1], reverse=True)  # 降序排序
 55         keylist = list()
 56         valueslist = list()
 57         for item in items:
 58             word, count = item
 59             #if word == ‘0‘:
 60                 #word = "其他"
 61             keylist.append(word)  # 把词语降序word放进一个列表
 62             valueslist.append(count)
 63         return keylist, valueslist
 64 
 65     #参数为 save_name 自动添加jpg 创建X条件词云,
 66     def city_wordcloud(self, save_name, condition):
 67         wordlist, giveup = self.extract_data_as_two_lis(condition)
 68         new_wordlist = list()
 69         for i in range(25):
 70             new_wordlist.append(wordlist[i])
 71         wl =  .join(wordlist)  # 把列表转换成str wl为str类型,所以需要转换
 72         cloud_mask = np.array(Image.open("love.jpg"))  # 词云的背景图,需要颜色区分度高
 73         wc = WordCloud(
 74             background_color="black",  # 背景颜色
 75             mask=cloud_mask,  # 背景图cloud_mask
 76             max_words=100,  # 最大词语数目
 77             font_path=msyh.ttc,  # 调用font里的simsun.tff字体,需要提前安装
 78             height=500,  # 设置高度
 79             width=2600,  # 设置宽度
 80             max_font_size=1000,  # 最大字体号
 81             random_state=1000,  # 设置随机生成状态,即有多少种配色方案
 82         )
 83         myword = wc.generate(wl)  # 用 wl的词语 生成词云
 84         # 展示词云图
 85         plt.imshow(myword)
 86         plt.axis("off")
 87         #plt.show()
 88         try:
 89             wc.to_file(save_name + .jpg)  # 把词云保存下当前目录(与此py文件目录相同)
 90         except:
 91             print("词云保存失败")
 92 
 93     #参数为condition ,创建柱形html图片,
 94     def pillar_picture(self, condition, render_name):
 95         from pyecharts.charts import Bar
 96         from pyecharts.globals import ThemeType
 97         from pyecharts import options as opts
 98 
 99         keylist, valueslist = self.extract_data_as_two_lis(condition)
100         new_keylist = list()
101         new_valueslist = list()
102         for i in range(10):
103             new_keylist.append(keylist[i])
104             new_valueslist.append(valueslist[i])
105         bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
106         # x轴 列表
107         bar.add_xaxis(new_keylist)
108         bar.add_yaxis("好友分布", new_valueslist)
109         # render 会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件
110         # 也可以传入路径参数,如 bar.render("mycharts.html")
111         bar.render(render_name)
112         print("pillar_picture图片保存成功!")
113 
114     #参数为condition,picture_name, keylist, valueslist, Map_condition->china或者广东创建html地图图片,图片名字为picture_name
115     def map_picture(self, condition, picture_name, keylist, valueslist, Map_condition):
116         from pyecharts import options as opts
117         from pyecharts.charts import Map
118 
119         def map_visualmap() -> Map:
120             new_keylist = list()
121             new_valueslist = list()
122             if condition == city:
123                 for i in range(len(keylist)):
124                     # 列表处理,默认elsx里面的city没有‘市‘字,地图需要市字
125                     new_keylist.append(keylist[i] + )
126                     new_valueslist.append(valueslist[i])
127             else:
128                 for i in range(len(keylist)):
129                     new_keylist.append(keylist[i])
130                     new_valueslist.append(valueslist[i])
131 
132             c = (
133                 Map()
134                     .add("好友地图分布", [list(z) for z in zip(new_keylist, new_valueslist)], Map_condition)
135                     .set_global_opts(
136                     title_opts=opts.TitleOpts(title="Map-VisualMap"),
137                     visualmap_opts=opts.VisualMapOpts(max_=100),
138                 )
139             )
140             try:
141                 c.render(picture_name)
142             except:
143                 print("html地图图片创建失败")
144             print(html地图图片保存成功)
145         map_visualmap()#调用自己
146 
147     #参数为condition,返回一个二维列表
148     def find_friends_in_condition(self, condition):
149         df = pd.read_excel(self.filename, usecols=[0, 1, 3], names=None)  #不要列名
150         df_li = df.values.tolist()
151         name = list()
152         for data in df_li:
153             condition = condition
154             if condition in data:
155                 name.append(data)
156         self.map_picture()
157         #print(len(name), name)
158         return name
159 
160 
161 if __name__ == "__main__":
162     wechat = wechat_test(wechat_info.xlsx, list)
163     wechat.friends_info_lis_to_excle()
164     wechat.city_wordcloud(city_wordclour, city)
165     wechat.pillar_picture(city, render.html)
166     keylist, valueslist = wechat.extract_data_as_two_lis(city)
167     wechat.map_picture(city, test.html, keylist, valueslist, "广东")
168     #wechat.find_friends_in_city()

4.结果如图所示

 

 技术图片

 

技术图片

 

技术图片

 

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

标签:列表   imp   lambda   展示   top   键值   col   charts   option   

原文地址:https://www.cnblogs.com/xiayiLL/p/10983061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!