python 玩转微信(一)

好友性别比例

python 玩转微信(一)_第1张图片

好友省份分布

python 玩转微信(一)_第2张图片

好友签名

python 玩转微信(一)_第3张图片

 代码部分

import itchat
import io
import jieba
import numpy as np
import matplotlib.pyplot as plt
import re
import PIL.Image as Image
from pyecharts import Pie, Map
from wordcloud import WordCloud, ImageColorGenerator

class WeiXin():
    def __init__(self):
        itchat.auto_login()
        self.friends = itchat.get_friends(update=True)[0:]
        self.sex = {"male": 0, "female": 0, "other": 0}  # 初始化性别
        self.city = self.get_data("City")  # 获取城市
        self.province = self.get_data("Province")  # 获取好友省份
        self.signature = self.get_data("Signature")  # 获取好友签名
        self.nickname = self.get_data("NickName")  # 获取好友昵称

    def get_sex(self):
        for item in self.friends:
            s = item["Sex"]
            if s == 1:
                self.sex["male"] += 1
            elif s == 2:
                self.sex["female"] += 1
            else:
                self.sex["other"] += 1
        attr = list(self.sex.keys())
        v1 = list(self.sex.values())
        pie = Pie("好友性别比例", title_pos="55%")
        pie.add(
            "",
            attr,
            v1,
            radius=[45, 65],
            center=[65, 50],
            legend_pos="80%",
            legend_orient="vertical",
        )
        pie.render('sex.html')

    def get_data(self, type):
        data = []
        for item in self.friends:
            data.append(item[type])
        return data

    def friends_province(self):
        province_distribution = {}
        for item in self.province:
            # 删除英文省份,因为中国地图表中没有
            if bool(re.search('[a-z]', item)):
                continue
            elif not province_distribution.__contains__(item):
                province_distribution[item] = 1
            else:
                province_distribution[item] += 1
        # 将省份名为空的删除
        province_distribution.pop('')
        # 提取地图接口需要的数据格式
        province_keys = province_distribution.keys()
        province_values = province_distribution.values()

        map = Map("我的微信好友分布", "", width=1200, height=600)
        map.add("", province_keys, province_values, maptype='china', is_visualmap=True, visual_text_color='#000')
        map.render('province.html')

    def parse_signature(self):
        siglist = []
        for i in self.friends:
            signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji", "")
            rep = re.compile("1f\d+\w*|[<>/=]")
            signature = rep.sub("", signature)
            siglist.append(signature)
        text = "".join(siglist)
        with io.open('text.txt', 'a', encoding='utf-8') as f:
            wordlist = jieba.cut(text, cut_all=True)
            word_space_split = " ".join(wordlist)
            f.write(word_space_split)
            f.close()

    def draw_signature(self):
        text = open(u'text.txt', encoding='utf-8').read()
        coloring = np.array(Image.open('signature.png'))
        my_wordcloud = WordCloud(background_color="white", max_words=2000,
                                 mask=coloring, max_font_size=60, random_state=42, scale=2,
                                 font_path="DroidSansFallbackFull.ttf").generate(text)
        image_colors = ImageColorGenerator(coloring)
        plt.imshow(my_wordcloud.recolor(color_func=image_colors))
        plt.imshow(my_wordcloud)
        plt.axis("off")
        plt.savefig('signature.png')
        plt.show()

    def generator(self):
        weixin.get_sex()
        weixin.friends_province()
        weixin.parse_signature()
        weixin.draw_signature()

weixin = WeiXin()
weixin.generator()





如果你的好友分布,图是这样的

python 玩转微信(一)_第4张图片

说明你有些库没有安装,执行下面命令即可

pip install echarts-countries-pypkg 
pip install echarts-china-provinces-pypkg
pip install echarts-china-cities-pypkg
pip install echarts-countries-pypkg 
pip install echarts-china-provinces-pypkg
pip install echarts-china-cities-pypkg

 

 

你可能感兴趣的:(Python,微信)