天天看點

itchat統計微信好友資訊

首先需要安裝itchat包,很簡單,pip就可以:

pip install itchat           

複制

基本資訊統計

代碼1

# -*- coding:utf-8 -*-
import itchat
from pandas import DataFrame


itchat.login()
friends = itchat.get_friends(update=True)[0:]
male = female = other = 0
for i in friends[1:]:
    sex = i['Sex']
    if sex == 1:
        male += 1
    elif sex == 2:
        female += 1
    else:
        other += 1

total = len(friends[1:])
malecol = round(float(male) / total * 100, 2)
femalecol = round(float(female) / total * 100, 2)
othercol = round(float(other) / total * 100, 2)
print('男性朋友:%.2f%%' % (malecol) +
      '\n' + '女性朋友:%.2f%%' % (femalecol) +
      '\n' + '性别不明的好友:%.2f%%' % (othercol))

# 使用echarts,加上這段
from echarts import Echart, Legend, Pie #pip install echarts-python

chart = Echart(u'%s的微信好友性别比例' % (friends[0]['NickName']), 'from WeChat')
chart.use(Pie('WeChat',
              [{'value': male, 'name': u'男性 %.2f%%' % malecol},
               {'value': female, 'name': u'女性 %.2f%%' % femalecol},
               {'value': other, 'name': u'其他 %.2f%%' % othercol}],
              radius=["50%", "70%"]))
chart.use(Legend(["male", "female", "other"]))
del chart.json["xAxis"]
del chart.json["yAxis"]
chart.plot()

def get_var(var):
    variable = []
    for i in friends:
        value = i[var]
        variable.append(value)
    return variable

NickName = get_var('NickName')#昵稱
Sex = get_var('Sex')#性别
Province = get_var('Province')#省份
City = get_var('City')#城市
Signature = get_var('Signature')#簽名

data = {'NickName': NickName,
        'Sex': Sex,
        'Province': Province,
        'City': City,
        'Signature': Signature
        }

frame = DataFrame(data)
frame.to_csv('data.csv', index=True, encoding="utf_8_sig")           

複制

好像不夠直覺,有興趣的朋友可以加上可視化的展示,我這裡用基于python的Echarts

先安裝了

pip install echarts-python           

複制

展示比例一般使用百分比圓餅表吧

# 使用echarts,加上這段
from echarts import Echart, Legend, Pie

chart = Echart(u'%s的微信好友性别比例' % (friends[0]['NickName']), 'from WeChat')
chart.use(Pie('WeChat',
              [{'value': male, 'name': u'男性 %.2f%%' % (float(male) / total * 100)},
               {'value': female, 'name': u'女性 %.2f%%' % (float(female) / total * 100)},
               {'value': other, 'name': u'其他 %.2f%%' % (float(other) / total * 100)}],
              radius=["50%", "70%"]))
chart.use(Legend(["male", "female", "other"]))
del chart.json["xAxis"]
del chart.json["yAxis"]
chart.plot()           

複制

itchat統計微信好友資訊

代碼2

# -*- coding:utf-8 -*-
import itchat
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt


#此時稍微等一會,會跳出一個二維碼,用手機微信掃描登入即可
itchat.login()
#friends裡面就是你的好友資訊啦,一共有36個字段,包括昵稱、你的備注、性别、地區、簽名、頭像位址等等
friends = itchat.get_friends(update=True)
df_friends = pd.DataFrame(friends)
#性别統計,0是未知,1是男生,2是女生
Sex_count = df_friends['Sex'].value_counts()
plt.figure(figsize=(16,8)) #設定圖檔大小
labels = ['male','female','unknown']
colors = ['red','yellowgreen','lightskyblue']
#畫性别分布餅圖
plt.pie(Sex_count,colors=colors,labels=labels,autopct = '%3.1f%%',startangle = 90,pctdistance = 0.8)
# 設定x,y軸刻度一緻,這樣餅圖才能是圓的
plt.axis('equal')
plt.legend(loc='left')
# plt.show() #這個注釋打開,下面無法儲存圖檔
plt.savefig('好友性别比例.jpg')

'''擷取好友的省份和地區分布'''
Province = df_friends.Province
Province_count = Province.value_counts()
#有一些好友地理資訊為空,過濾掉這一部分人
Province_count = Province_count[Province_count.index!='']
df_province =DataFrame(Province_count)
df_province.to_csv('省份分布.csv',encoding='utf-8')

City = df_friends.City
City_count = City.value_counts()
City_count = City_count[City_count.index!='']

#統計好友基本資訊
number_of_friends = len(friends)
NickName = friends[0]['NickName'] #擷取自己的昵稱
file_name_all = NickName+'_basic_inf.txt'

with open(file_name_all,'w') as f:
    f.write('你共有%d個好友,其中有%d個男生,%d個女生,%d未顯示性别。\n\n' %(number_of_friends, Sex_count[1], Sex_count[2], Sex_count[0]))

    f.write('你的朋友主要來自省份:%s(%d)、%s(%d)和%s(%d)。\n\n' %(Province_count.index[0],Province_count[0],Province_count.index[1],
     Province_count[1],Province_count.index[2],Province_count[2]))

    f.write('主要來自這些城市:%s(%d)、%s(%d)、%s(%d)、%s(%d)、%s(%d)和%s(%d)。'%(City_count.index[0],City_count[0],City_count.index[1],
     City_count[1],City_count.index[2],City_count[2],City_count.index[3],City_count[3],City_count.index[4],City_count[4],City_count.index[5],City_count[5]))           

複制

itchat統計微信好友資訊

個性簽名和昵稱分布

# -*- coding:utf-8 -*-
import jieba,re,itchat
import numpy as np
from collections import defaultdict
from wordcloud import WordCloud, ImageColorGenerator
import PIL.Image as Image
import matplotlib.pyplot as plt
from pandas import DataFrame
import pandas as pd


#此時稍微等一會,會跳出一個二維碼,用手機微信掃描登入即可
itchat.login()
#friends裡面就是你的好友資訊啦,一共有36個字段,包括昵稱、你的備注、性别、地區、簽名、頭像位址等等
friends = itchat.get_friends(update=True)
df_friends = pd.DataFrame(friends)
Signatures = df_friends.Signature
regex1 = re.compile('<span.*?</span>') #比對表情
regex2 = re.compile('\s{2,}')#比對兩個以上占位符。
#用一個空格替換表情和多個空格。
Signatures = [regex2.sub(' ',regex1.sub('',signature,re.S)) for signature in Signatures]
Signatures = [signature for signature in Signatures if len(signature)>0] #去除空字元串
text = ' '.join(Signatures)
wordlist = jieba.cut(text, cut_all=False)

def statistics(lst) :
    dic = {}
    for k in lst:
        if not k.decode('utf-8') in dic :
            dic[k.decode('utf-8')] = 0
        dic[k.decode('utf-8')] +=1
    return dic

worddic = statistics(wordlist)

coloring = np.array(Image.open("./xiaodong.jpg"))#詞雲的背景和顔色,需要提前自己找好
my_wordcloud = WordCloud(background_color="white", max_words=2000,
              mask=coloring, max_font_size=200, random_state=8, scale=2,
              font_path="./songti.otf").generate_from_frequencies(worddic)

image_colors = ImageColorGenerator(coloring)

plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
my_wordcloud.to_file('簽名分詞.png')
#---------------------------------------------------
'''換一種詞雲産生方式,将關鍵詞放大比例顯示'''
word_space_split = ' '.join(wordlist)
coloring = np.array(Image.open("./xiaodong.jpg")) #詞雲的背景和顔色。這張圖檔在本地。
my_wordcloud = WordCloud(background_color="white", max_words=2000,
             mask=coloring, max_font_size=60, random_state=42, scale=2,
             font_path="./songti.otf").generate(word_space_split)

my_wordcloud.to_file('關鍵詞簽名分詞.jpg') #儲存圖檔

#--------------------------------------昵稱雲圖-------------------------------------------------------
Nicknames = df_friends.NickName
regex1 = re.compile('<span.*?</span>') #比對表情
regex2 = re.compile('\s{2,}')#比對兩個以上占位符。
#用一個空格替換表情和多個空格。
Nicknames = [regex2.sub(' ',regex1.sub('',nickname,re.S)) for nickname in Nicknames]
Nicknames = [nickname for nickname in Nicknames if len(nickname)>0] #去除空字元串
text_nicknames = ''.join(Nicknames)
a = re.compile(' ')
text_nicknames = a.sub('',text_nicknames)

def save_chinese(text):
    text = text.decode('utf-8')
    a = re.compile(u"[\u4E00-\u9FA5]+")
    text = a.findall(text)
    text=''.join(text)
    return text

text_nicknames = save_chinese(text_nicknames)

def get_count(Sequence):
    counts = defaultdict(int) #初始化一個字典
    for x in Sequence:
        counts[x] += 1

    return counts

nickname_count = get_count(text_nicknames)
#nickname_count_s = sorted(nickname_count.iteritems(), key=lambda d:d[1], reverse = True)
coloring = np.array(Image.open("./xiaodong.jpg"))#詞雲的背景和顔色,需要提前自己找。
nm_wordcloud = WordCloud(background_color="white", max_words=2000,
               mask=coloring, max_font_size=200, random_state=8, scale=2,
               font_path="./songti.otf").generate_from_frequencies(nickname_count)

# image_colors = ImageColorGenerator(coloring)
#plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(nm_wordcloud)
plt.axis("off")
plt.show()
nm_wordcloud.to_file('昵稱雲圖.png')           

複制

itchat統計微信好友資訊
itchat統計微信好友資訊

好友頭像拼接

# -*- coding:utf-8 -*-
import itchat,math,os
import PIL.Image as Image


itchat.auto_login()
friends = itchat.get_friends(update=True)[0:]
user = friends[0]["UserName"]

num = 0
for i in friends:
    img = itchat.get_head_img(userName=i["UserName"])
    fileImage = open(r'./img/'+ str(num) + ".jpg",'wb')
    fileImage.write(img)
    fileImage.close()
    num += 1

ls = os.listdir(r'./img/')
each_size = int(math.sqrt(float(640*640)/len(ls)))
lines = int(640/each_size)
image = Image.new('RGBA', (640, 640))
x = 0
y = 0
for i in range(0,len(ls)+1):
    try:
        img = Image.open(r'./img/'+ str(i) + ".jpg")
    except IOError:
        print("Error")
    else:
        img = img.resize((each_size, each_size), Image.ANTIALIAS)
        image.paste(img, (x * each_size, y * each_size))
        x += 1
        if x == lines:
            x = 0
            y += 1
image.save(r'./img/'+ "all.jpg")
itchat.send_image(r'./img/'+ "all.jpg", 'filehelper')           

複制

itchat統計微信好友資訊

參考:https://zhuanlan.zhihu.com/p/26514576

https://zhuanlan.zhihu.com/p/33230381