University Rankings

1. Using the library

① wxpy: micro-channel initialization robot

② openpyxl: micro-channel friend save data to an Excel spreadsheet

③ pyecharts: generating a visual map

④ wordcloud, matplotlib, jieba: generate word cloud

[ Remind ]: pyecharts library using a 0.5.x version, installed pip for 1.xx version, it is necessary to own [ official website ] to download.

2. Basic functions

① micro-channel buddy data analysis

② generate word cloud

③ generate a map showing

3. code implementation

As used herein classes to implement

(1) Import Module

Copy the code
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
Copy the code

 

(2) initialization of the robot and the information acquisition source micro-letter friends

Bot here call () method, you need to sweep the yard landing micro letter web version, subsequent operations can take place.

Copy the code
. 1 DEF the __init __ (Self, ToExcelFile = "", ToCityFile = "", ToMapProvinceFile = "", ToMapCityFile = ""): 
 2 '' 'initialization robots and other parameters' '' 
 3 # initialization robot needs scan code 
 4 self. = Bot. BOT () 
 . 5 # I acquired all micro-channel buddy information - storing basic information (untreated) 
 . 6 = self.bot.friends self.allFriends_Info () 
 . 7 # my friends micro-channel number 
 8 self.allFriends_Num = len (self .allFriends_Info) 
 spreadsheet files saved path # 9 micro-letter friends information (.xlsx) 
10 self.ExcelFile = ToExcelFile 
word cloud file path to save the city # 11 (.png / .jpg) 
12 self.WCOfCityFile = ToCityFile 
13 # save provinces file path (.html) 
14 self.MapProvinceFile ToMapProvinceFile = 
15 # other useful parameters 
16 self.= ToMapCityFile MapCityFile 
. 17 # automatically call the run method, such operation automatically instantiated objects other functionsMapCityFile = ToMapCityFile
18     self.run()
Copy the code

 

(3) Statistical processing and micro-channel information friends

In addition there are personalized signature, head of listed and other additional properties.

Copy the code
DEF getFriendsInfo. 1 (Self): 
 2 '' 'Get Friends all available micro-letter' '' 
 3 # store micro channel buddy information (processed information) 
 . 4 self.friendsInfo = [] 
 . 5 # define the column headings 
 6 self.infoTitle = [ 'the nickName', 'RemarkName', 'Sex', 'Province', 'City'] 
 . 7 for afriend in self.allFriends_Info: 
 . 8 # nickname acquisition 
 9 nickName = aFriend.raw.get (self.infoTitle [0 ], None ) 
10 acquires Remark # 
. 11 RemarkName = aFriend.raw.get (self.infoTitle [. 1], None) 
12 is acquired gender # 
13 sex = {1: "M", 2: "female" 0: "others"}. GET (aFriend.raw.get (self.infoTitle [2], None), None) 
14 # Get provinces 
15 province = aFriend.raw.get (self.infoTitle [3 ],None) 
16 # obtain city
17         City = aFriend.raw.get(self.infoTitle[4], None)
18         lisTmp = [NickName, RemarkName, Sex, Province, City]
19         self.friendsInfo.append(lisTmp)
Copy the code

 

(4) save information WeChat friends

This is stored in an Excel spreadsheet, the code in the header row insert for ease of reading.

Copy the code
DEF saveFriendsInfoAsExcel. 1 (Self, ExcelName): 
 2 '' 'to save the information to the micro-channel buddy Excel spreadsheet' '' 
 3 # openpyxl generated objects 
 . 4 Workbook openpyxl.Workbook = () 
 . 5 # activate the table 
 . 6 Sheet = workbook.active 
 . 7 # set table title 
 . 8 sheet.title = 'WeChatFriendsInfo' 
 . 9 # filled column heading to the first line 
10 for _ in Range (len (self.infoTitle)): 
. 11 sheet.cell (row =. 1, column = _ +. 1, value self.infoTitle = [_]) 
12 is filled with micro-channel # buddy information, starting from the second row 
13 is for I in Range (self.allFriends_Num): 
14 for J in Range (len (self.infoTitle)): 
15 sheet.cell ( 2 = I + Row, column = + J. 1, value = STR (self.friendsInfo [I] [J])) 
16 # If the file name is not empty, it is saved to the path 
17 if ExcelName = ""!:
18         workbook.save(ExcelName)
19         print(">>> Save WeChat friends' information successfully!")
Copy the code

 

(5) Analysis of the micro-channel information friends

DEF quiteAnalyzeFriendsInfo. 1 (Self): 
2 '' 'analysis data, one step, straightforward' '' 
. 3 Print (self.allFriends_Info.stats_text ())

 

(6) to generate word cloud city

Copy the code
DEF creatWordCloudOfCity. 1 (Self, the CityName): 
 2 '' 'using the acquired data word cloud generation city' '' 
 3 # overview of all cities 
 . 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 library fine mode segmentation 
 . 9 wordlist = jieba.lcut (cityStr) 
10 cityStr = '' .join (wordlist) 
11 # loaded background image 
12 #cloud_mask = np.array (Image.open (BackGroundFile)) 
13 # set word cloud properties 
14 font = r'C: \ Windows \ fonts \ simfang.ttf '# set the font path 
15 wordcloud = WC ( 
16 BACKGROUND_COLOR = 'Black',The background color # 
17 #mask = cloud_mask, # background image
18 max_words = 100, # set the number of word cloud maximum displayable 
19 font_path = font, # set the font format (in the present machine system) 
20 is height = 300, # picture height 
21 width = 600, # Image Width 
22 max_font_size = 100, maximum font # 
23 random_state = 100, the color scheme of the type # 
24) 
25 to generate the word cloud # 
26 is myWord = wc.generate (cityStr) 
27 # word cloud display 
28 plt.imshow (myWord) 
29 plt.axis ( 'OFF' ) 
30 plt.show () 
31 is not empty # If the file name, the path is saved to the next 
32 IF the CityName = "":! 
33 is stored word cloud # 
34 wc.to_file (CityName)
35         print(">>> Creat WeChat wordcloud of city successfully!")
Copy the code

 

(7) generating province map

Copy the code
DEF creatMapProvince. 1 (Self, the MapFile): 
 2 '' 'using the acquired map data generating province' '' 
 3 # Get all the provinces 
 . 4 provinceList, provinceNum = [], [] 
 . 5 for I in (self.allFriends_Num) Range: 
 . 6 self.friendsInfo IF [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 Range in (len (provinceList)): 
. 11 IF self.friendsInfo [I] [. 3] == provinceList [J]: 
12 is provinceNum [J] +. 1 = 
13 is generated # the Map 
14 the Map Map = ( "friends provincial distribution of micro-channel" , width = 1000, height = 800 )
Map.add 15 ( "", provinceList, provinceNum, maptype = "china", is_visualmap = True, visual_text_color = '# 000') 
16 # If the file name is not empty, then save it to the path 
17 if MapFile! = "" : 
18 map.render (MapFile) 
19 Print ( ">>> Creat WeChat the Map of Provinces seccessfully!")
Copy the code

 

(8) generating city map

Copy the code
DEF creatMapCity. 1 (Self, the MapFile): 
 2 '' 'using the acquired map data generating city' '' 
 3 # Get all the provinces 
 . 4 CityList, CityNum = [], [] 
 . 5 for I in (self.allFriends_Num) Range: 
 . 6 self.friendsInfo IF [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 Range in (len (CityList)): 
. 11 IF self.friendsInfo [I] [. 4] == CityList [J]: 
12 is CityNum [J] +. 1 = 
13 is for I in Range (len (CityList)): 
14 CityList [ i] + = 'si' 
15 generates Map #
16 map = Map ( "micro-channel buddy profile cities", width = 1000, height = 800) 
. 17 map.add ( "", CityList, CityNum, MapType = "Guangdong", is_visualmap = True, visual_text_color = '# 000') 
18 is # If the file name is not empty, then save it to the path 
19 IF MapFile = "!": 
20 map.render (MapFile) 
21 Print ( "! >>> Creat WeChat seccessfully the Map of Cities")
Copy the code

With the above method to realize various functions, so he sent a variety of methods it is called.

(9) run method

Copy the code
RUN DEF. 1 (Self): 
 2 # friend information acquiring micro-channel 
 . 3 self.getFriendsInfo () 
 . 4 Print ( ">>> WeChat the Get Friends' Information successfully!") 
 . 5 Print ( ">>> Members:", self.allFriends_Num) 
 save micro-channel # 6 buddy information 
 . 7 self.saveFriendsInfoAsExcel (self.ExcelFile) 
 . 8 # micro analysis buddy information channel 
 . 9 self.quiteAnalyzeFriendsInfo () 
10 # friends using micro-letter word cloud generation city 
. 11 self.creatWordCloudOfCity (self.WCOfCityFile) 
12 is generated micro-channel # friends province map 
13 is self.creatMapProvince (self.MapProvinceFile) 
14 # to generate micro-letter friends city map 
15 self.creatMapCity (self.MapCityFile)
Copy the code

For the file path, can be transmitted in the main function. [Note]: The above code in the class, where the end of the following main function

Copy the code
IF __name__ == 1 "__main__": 
2 ToExcelFile = "./WeChatAnalyze//FriendsInfo.xlsx" Excel spreadsheet saved path # micro-letter friends information 
3 ToPictureFile = "./WeChatAnalyze//CityWordCloud.png" # micro-letter word friend Information city cloud save path 
4 ToMapFileProvince = "./WeChatAnalyze//WeChatProvinceMap.html" # WeChat province friend information stored map path 
5 ToMapFileCity = "./WeChatAnalyze//WeChatCityMap.html" # WeChat friend information stored city maps path 
6 # WeChatRobot object instance of 
7 robot = WeChatRobot (ToExcelFile, ToPictureFile , ToMapFileProvince, ToMapFileCity)
Copy the code

It is not that the Main function is very short, ha ha, yes, that is so simple!

Then look at the effect achieved it!

This is the display terminal >>>

>>> This is saved as an Excel spreadsheet content

 >>> This is the distribution of micro-letter friends provinces

>>> This is the distribution of micro-letter friends municipalities

 

OK. This is to share it today! Finally, attach the complete code!

 

references:

① micro-channel play with Python: https://segmentfault.com/a/1190000014203617

② pyecharts 中部分import 不到:https://blog.csdn.net/weixin_38617311/article/details/81146748

③ pyecharts 中地图显示不全:https://blog.csdn.net/xiamoyanyulrq/article/details/80025105

 

# -*- coding: utf-8 -*-
'''
This is a program which can analyze datas of WeChat friends.
@author: bpf
'''
#  导入模块
from wxpy import Bot
import openpyxl
from pyecharts import Map
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba
class WeChatRobot:
    '''====================== 1. 获取微信好友信息 ======================'''
    def __init__(self, ToExcelFile="", ToCityFile="", ToMapProvinceFile="", ToMapCityFile=""):
        ''' 初始化机器人和其他参数 '''
        # 初始化机器人,需要扫码
        self.bot = Bot()
        # 获取我所有的微信好友信息 - 存储基础信息(未处理)
        self.allFriends_Info = self.bot.friends()
        # 我的微信好友个数
        self.allFriends_Num = len(self.allFriends_Info)
        # 保存微信好友信息的表格文件路径(.xlsx)
        self.ExcelFile = ToExcelFile
        # 保存城市词云图的文件路径(.png/.jpg)
        self.WCOfCityFile = ToCityFile
        # 保存省份地图的文件路径(.html)
        self.MapProvinceFile = ToMapProvinceFile
        # 其他可用参数
        self.MapCityFile = ToMapCityFile
        # 自动调用run方法,使得在实例化对象后自动运行其他函数
        self.run()
    '''====================== 2. 统计微信好友信息 ======================'''
    def getFriendsInfo(self):
        ''' 获取微信好友的全部信息 '''
        # 存储微信好友的信息(经过信息处理的)
        self.friendsInfo = []
        # 定义列标题
        self.infoTitle = ['NickName', 'RemarkName', 'Sex', 'Province', 'City']
        for aFriend in self.allFriends_Info:
            # 获取昵称
            NickName = aFriend.raw.get(self.infoTitle[0], None)
            # 获取备注
            RemarkName = aFriend.raw.get(self.infoTitle[1], None)
            # 获取性别
            Sex = {1:"男", 2:"女", 0:"其他"}.get(aFriend.raw.get(self.infoTitle[2], None), None)
            # 获取省份
            Province = aFriend.raw.get(self.infoTitle[3], None)
            # 获取城市
            City = aFriend.raw.get(self.infoTitle[4], None)
            lisTmp = [NickName, RemarkName, Sex, Province, City]
            self.friendsInfo.append(lisTmp)
   
    '''====================== 3. 保存微信好友信息 ======================'''
    def saveFriendsInfoAsExcel(self, ExcelName):
        ''' 保存微信好友的信息到 Excel 表格中 '''
        # 生成openpyxl对象
        workbook = openpyxl.Workbook()
        # 激活表格
        sheet = workbook.active
        # 设置表格标题
        sheet.title = 'WeChatFriendsInfo'
        # 填充列标题到第一行
        for _ in range(len(self.infoTitle)):
            sheet.cell(row=1, column=_+1, value=self.infoTitle[_])
        # 填充微信好友信息,从第二行开始
        for i in range(self.allFriends_Num):
            for j in range(len(self.infoTitle)):
                sheet.cell(row=i+2, column=j+1, value=str(self.friendsInfo[i][j]))
        # 若文件名非空,则保存到该路径下
        if ExcelName != "":
            workbook.save(ExcelName)
            print(">>> Save WeChat friends' information successfully!")
    '''====================== 4. 分析微信好友信息 ======================'''
    def quiteAnalyzeFriendsInfo(self):
        ''' 分析数据,一步到位,直接了当 '''
        print(self.allFriends_Info.stats_text())
   
    '''====================== 5. 产生city词云图 ======================'''
    def creatWordCloudOfCity(self, CityName):
        ''' 使用获取的数据生成city词云图 '''
        # 获取所有的城市
        cityStr = ""
        for i in range(self.allFriends_Num):
            if self.friendsInfo[i][4] not in cityStr:
                cityStr += " " + self.friendsInfo[i][4]
        #jieba库精确模式分词
        wordlist = jieba.lcut(cityStr)
        cityStr = ' '.join(wordlist)
        # 加载背景图片
        #cloud_mask = np.array(Image.open(BackGroundFile))
        #设置词云图属性
        font = r'C:\Windows\Fonts\simfang.ttf' # 设置字体路径
        wc = WordCloud(
            background_color = 'black',     # 背景颜色
            #mask = cloud_mask,             # 背景图片
            max_words = 100,                # 设置最大显示的词云数
            font_path = font,               # 设置字体形式(在本机系统中)
            height = 300,                   # 图片高度
            width = 600,                    # 图片宽度
            max_font_size = 100,            # 字体最大值
            random_state = 100,             # 配色方案的种类
            )
        # 生成词云图
        myword = wc.generate(cityStr)
        #展示词云图
        plt.imshow(myword)
        plt.axis('off')
        plt.show()
        # 若文件名非空,则保存到该路径下
        if CityName != "":
            #保存词云图
            wc.to_file(CityName)
            print(">>> Creat WeChat wordcloud of city successfully!")
   
    '''===================== 6. 产生province地图 ====================='''
    def creatMapProvince(self, MapFile):
        ''' 使用获取的数据生成province地图 '''
        # 获取所有省份
        provinceList, provinceNum = [], []
        for i in range(self.allFriends_Num):
            if self.friendsInfo[i][3] not in provinceList:
                provinceList.append(self.friendsInfo[i][3])
                provinceNum.append(0)
        for i in range(self.allFriends_Num):
            for j in range(len(provinceList)):
                if self.friendsInfo[i][3] == provinceList[j]:
                    provinceNum[j] += 1
        # 生成 Map
        map = Map("各省微信好友分布", width=1000, height=800)
        map.add("", provinceList, provinceNum, maptype="china", is_visualmap=True, visual_text_color='#000')
        # 若文件名非空,则保存到该路径下
        if MapFile != "":
            #map.show_config()
            map.render(MapFile)
            print(">>> Creat WeChat Map of Provinces seccessfully!")
   
    '''===================== 7. 产生city地图 ====================='''
    def creatMapCity(self, MapFile):
        ''' 使用获取的数据生成city地图 '''
        # 获取所有省份
        CityList, CityNum = [], []
        for i in range(self.allFriends_Num):
            if self.friendsInfo[i][4] not in CityList:
                CityList.append(self.friendsInfo[i][4])
                CityNum.append(0)
        for i in range(self.allFriends_Num):
            for j in range(len(CityList)):
                if self.friendsInfo[i][4] == CityList[j]:
                    CityNum[j] += 1
        for i in range(len(CityList)):
            CityList[i] += '市'
        # 生成 Map
        map = Map("各市微信好友分布", width=1000, height=800)
        map.add("", CityList, CityNum, maptype="广东", is_visualmap=True, visual_text_color='#000')
        # 若文件名非空,则保存到该路径下
        if MapFile != "":
            map.render(MapFile)
            print(">>> Creat WeChat Map of Cities seccessfully!")
       
    '''===================== 8. 自动执行函数 ====================='''
    def run(self):
        # 获取微信好友信息
        self.getFriendsInfo()
        print(">>> Get WeChat friends' information successfully!")
        print(">>> Members:", self.allFriends_Num)
        # 保存微信好友信息
        self.saveFriendsInfoAsExcel(self.ExcelFile)
        # 分析微信好友信息
        self.quiteAnalyzeFriendsInfo()
        # 使用微信好友的 city 产生词云图
        self.creatWordCloudOfCity(self.WCOfCityFile)
        # 生成微信好友的 province 地图
        self.creatMapProvince(self.MapProvinceFile)
        # 生成微信好友的 city 地图
        self.creatMapCity(self.MapCityFile)
       
if __name__ == "__main__":
    ToExcelFile = "./WeChatAnalyze//FriendsInfo.xlsx"      # 微信好友信息的Excel表格保存路径
    ToPictureFile = "./WeChatAnalyze//CityWordCloud.png"   # 微信好友信息city词云图保存路径
    ToMapFileProvince = "./WeChatAnalyze//WeChatProvinceMap.html" # 微信好友信息province地图保存路径
    ToMapFileCity = "./WeChatAnalyze//WeChatCityMap.html"  # 微信好友信息city地图保存路径
    # WeChatRobot object instantiation
    robot = WeChatRobot (ToExcelFile, ToPictureFile, ToMapFileProvince, ToMapFileCity)

Guess you like

Origin www.cnblogs.com/luorunsb/p/10968775.html