想了解你微信好友吗?进来看看吧~
#模拟微信登入
import itchat
from pandas import DataFrame
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']#绘图时可以显示中文
plt.rcParams['axes.unicode_minus']=False#绘图时可以显示中文
import re
#微信二维码登入入口
itchat.login()
#获取微信好友信息
friends = itchat.get_friends(update=True)[0:]
获取微信好友性别,结果如下:
#统计微信好友性别
male = female = other = 0
for i in friends:
sex = i['Sex']
if sex == 1:
male+=1
elif sex == 2:
female += 1
else:
other += 1
print('friends total number is {} \n male number is:{}\n female number is:{}\n other number is:{}\n'.format(len(friends),male,female,other))
friends[1]
total = len(friends[:])
print('男性好友:%.2f%%'%(float(male)/ total*100)+'\n'+
'女性好友:%.2f%%'%(float(female)/total*100)+'\n'+
'不明性别的好友:%.2f%%'%(float(other) / total*100))
运行结果如下:
关于微信好友性别统计的另一种写法,并通过饼图展示:
from pyecharts import Pie
sexs=list(map(lambda x:x['Sex'],friends[1:])) #提取好友性别
value = [sexs.count(1), sexs.count(2), sexs.count(0)]#对性别进行计数
sex_attr=['male','female','unknown']
pie = Pie('好友性别比例', '好友总人数:%d' % len(sex), title_pos='center')
pie.add('', sex_attr, value, radius=[30, 75], rosetype='area', is_label_show=True,is_legend_show=True, legend_top='bottom')
# pie.show_config()
pie
pie.render('好友性别比例.html')
获取需要统计的维度:备注、昵称、性别、省份、城市、签名、头像等
def get_var(var):
variable = []
for i in friends:
value = i[var]
variable.append(value)
return variable
Remark_name = get_var('RemarkName')
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(r'.\data.csv',index = True)
frame['Province'].value_counts()
frame['City'].value_counts()
frame['NickName'].value_counts()
#friends[0]['Signature'].strip().replace('span','').replace('class','').replace('emoji','')
from pyecharts import Bar
from collections import Counter
city_5=Counter(city).most_common(5)
# 返回出现次数最多的20条
bar = Bar('好友所在城市TOP5', '', title_pos='center', width=800, height=500)
attr, value = bar.cast(city_5)
bar.add('', attr, value, is_visualmap=True, visual_text_color='#fff', is_more_utils=True,is_label_show=True)
bar.render('好友所在城市TOP10.html')
dir(bar)
结果如图所示,由于城市地址设计个人隐私这里就不显示啦~
也可将好友所在省份在地图上展示,调用Map模块:
#好友地理位置分析
from pyecharts import Map
provinces_count = data.groupby('province', as_index=True)['province'].count().sort_values()
provinces_count
attr = list(map(lambda x: x if x != '' else '未知', list(provinces_count.index)))#未填写地址的改为未知
value = list(provinces_count)
map_1 = Map("微信好友位置分布图",title_pos="center",width=1000, height=500)
map_1.add('', attr, value, is_label_show=True, is_visualmap=True, visual_text_color='#000',visual_range=[0,120])
map_1.render(path=r'D:\chengmi_吴限\python\personal_python\itchat\微信好友分布.html')
######################
from pyecharts import Map
def get_attr(friends, key):
return list(map(lambda user: user.get(key), friends))
def fun_pos(friends):
users = dict(province=get_attr(friends, "Province"),
city=get_attr(friends, "City"),
nickname=get_attr(friends, "NickName"))
provinces = pd.DataFrame(users)
provinces_count = provinces.groupby('province', as_index=True)['province'].count().sort_values()
attr = list(map(lambda x: x if x != '' else '未知', list(provinces_count.index)))#未填写地址的改为未知
value = list(provinces_count)
map_1 = Map("微信好友位置分布图",title_pos="center",width=1000, height=500)
map_1.add('', attr, value, is_label_show=True, is_visualmap=True, visual_text_color='#000',visual_range=[0,120])
map_1.render(path=r'D:\chengmi_吴限\python\personal_python\itchat\好友分布.html')
fun_pos(friends)
== 结果显示,有数据但是地图调用未成功,此问题更进中 ==
利用结巴分词split签名:
import re
siglist = []
for i in 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)
import jieba
wordlist = jieba.cut(text,cut_all=True)
word_space_split =" ".join(wordlist)
type(word_space_split)
import numpy as np
import os
def save_fig(fig_id, tight_layout=True):
path = os.path.join(r".\itchat", fig_id + ".png")
print("Saving figure", fig_id)
if tight_layout:
plt.tight_layout()
plt.savefig(path, format='png', dpi=300)
利用词云将分词好的词语用图片展示出来:
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
import PIL.Image as Image
coloring = np.array(Image.open(r'.\电商.jpg'))
my_wordcloud = WordCloud(background_color='white',max_words=200,mask=coloring,max_font_size=60,random_state=42,
scale=2,font_path=r'C:\Windows\Fonts\simkai.ttf').generate(word_space_split)
image_colors = ImageColorGenerator(coloring)
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis('off')
save_fig('my_wordcloud_0')
plt.show()
犬夜叉原图:
生成后的效果:
对好友人生观做一个简单分析
from wordcloud import WordCloud
from wordcloud import ImageColorGenerator
import jieba
import jieba.analyse
import snownlp
from pyecharts import Bar
import PIL.Image as Image
signatures = ''
emotions = []
for friend in friends:
signature = friend['Signature']
if signature != None:
signature = signature.strip().replace("span","").replace("class","").replace("emoji","")#去除无关数据
signature = re.sub(r'1f(\d.+)',"",signature)
if len(signature) > 0:
nlp = snownlp.SnowNLP(signature)
emotions.append(nlp.sentiments)#nlp.sentiments:权值
signatures += " ".join(jieba.analyse.extract_tags(signature,5)) #关键字提取
back_coloring = np.array(Image.open('D:\chengmi_吴限\python\personal_python\itchat\Image1.jpg','r'))#图片可替换
word_cloud2 = WordCloud(background_color='white',max_words=200,mask=back_coloring,max_font_size=60,random_state=42,
scale=2,font_path=r'C:\Windows\Fonts\simkai.ttf')
word_cloud2.generate(signatures)
image_colors = ImageColorGenerator(back_coloring)
plt.figure(figsize=(6,5),dpi=160)
plt.imshow(word_cloud2.recolor(color_func=image_colors))
plt.axis("off")
plt.show()
word_cloud2.to_file("signatures.jpg")
#人生观
count_positive = len(list(filter(lambda x:x>0.66,emotions)))#大于0.66为积极
count_negative = len(list(filter(lambda x:x<0.33,emotions)))#小于0.33为消极
count_neutral = len(list(filter(lambda x:x>=0.33 and x <= 0.66,emotions)))
value=[count_positive,count_negative,count_neutral]
att_attr=['积极','消极','中性']
bar=Bar('个性签名情感分析',title_pos='center',width=1000,height=500)
bar.add('', att_attr, value, visual_range=[0, 200], is_visualmap=True, is_label_show=True)
#bar.add(",att_attr,value,visual_range=[0, 200], is_visualmap=True, is_label_show=True)
dir(bar)
bar.render(path=r'D:\chengmi_吴限\python\personal_python\itchat\人生观分布.html')
a=bar.show_config()
结果展示:
下载好友头像识别人脸
#下载好友头像
basePath = os.path.abspath('.')
baseFolder = basePath + '\\HeadImages\\'
if(os.path.exists(baseFolder) == False):
os.makedirs(baseFolder)
# Analyse Images
image_tags = ''
for index in range(1,2):
friend = friends[index]
# Save HeadImages
imgFile = baseFolder + '\\Image%s.jpg' % str(index)
imgData = itchat.get_head_img(userName = friend['UserName'])
if(os.path.exists(imgFile) == False):
with open(imgFile,'wb') as file:
file.write(imgData)
from PIL import Image
import matplotlib.pyplot as plt
img=Image.open("D:\chengmi_吴限\python\personal_python\itchat\Image1.jpg")
plt.figure("好友头像")
plt.imshow(img)
plt.show()
from aip import AipFace
import base64
APP_ID = "16817541"
API_KEY = "3aCALRTRMHkdoyTSwMQpe0Kt" #请替换为自己的apikey,注册地址https://login.bce.baidu.com/?account=
SECRET_KEY = "4ZwfXGtWg9HmpqnE26kegKvam4TmzR2C"
client = AipFace(APP_ID, API_KEY, SECRET_KEY) #初始化aipface对象
filepath = "D:\chengmi_吴限\python\personal_python\itchat\image2.jpg"
with open(filepath, "rb") as fp:
base64_data = base64.b64encode(fp.read())
image = str(base64_data, 'utf-8')
imageType = "BASE64"
options = {}
options["face_field"] = "age,gender,beauty,expression"
options["max_face_num"] = 10
options["face_type"] = "LIVE"
result = client.detect(image, imageType, options)
print(result)
dir(result)
import pandas as pd
facelist=result['result']['face_list']
output=pd.DataFrame(facelist)
output.columns
output.drop(['angle','face_token'],axis=1,inplace=True)
output.head()
output['age'] # 年龄
output['beauty'] # 美丑打分,范围0-100,越大表示越美
output['face_probability'] #人脸置信度,范围【0~1】,代表这是一张人脸的概率,0最小、1最大。
output['gender'] #probability,性别置信度,范围【0~1】,0代表概率最小、1代表最大。
output['location'] #人脸在图片中的位置
# /*具体参数,可参考百度智能云接口文档*/
# 链接:https://cloud.baidu.com/doc/FACE/s/4jwvxqu69
这里随便在网上找了明星的图片,图如下:
结果展示如下:
年龄显示结果是满满的年轻啊,检测到人脸的置信度均大于0.97,且是女性的可能性极高。
###############展示人脸识别的图像#######################
import cv2
import matplotlib.pyplot as plt
img=cv2.imread('faces.jpg')
location=result['result']['face_list'][0]['location']
left_top=(location['left'],location['top'])
right_bottom=(left_top[0]+location['width'],left_top[1]+location['height'])
cv2.rectangle(img,(283.06,219),(328,264),(255,0,0),2)
#图片中人脸,cvRectangle函数参数: 图片, 左上角, 右下角, 颜色, 线条粗细, 线条类型,点类型
cv2.rectangle(img,(400.94,40),(246,80),(255,0,0),2)
cv2.rectangle(img,(181.72,40),(384,85),(255,0,0),2)
cv2.rectangle(img,(26.52,190),(194,230),(255,0,0),2)
#cv2.imshow('img',img)
plt.imshow(img)
plt.show()