当前位置: 首页 > 后端技术 > Python

使用Python获取微信好友数据,可视化分析发现~

时间:2023-03-25 23:27:15 Python

大家好!因为闲着没事,就想看看爬取微信好友,然后理性分析一下~~01数据收集我们这次使用了Itchat库来获取微信好友数据。01登录使用Itchat库获取微信好友数据,需要先登录。代码如下:itchat.auto_login(hotReload=True)hotReload=True的作用是短时间内获取数据,不需要重复登录验证。02获取好友数据Itchat库的get_friends()函数可以获取所有好友的数据。但是它获取到的数据类型是Itchat类型,因为我们不需要使用正则表达式来提取数据,所以我们需要将数据转换成字符串类型,代码如下:all_friends=str(itchat.get_friends())至此,我们就可以提取数据了。这里我们提取了朋友的签名,朋友的性别,朋友的省市。这四个数据用于可视化显示。代码如下:#signatureSignature=re.findall("'Signature':'([\u4e00-\u9fa5].*?)',",all_friends)c=0foriinSignature:withopen(r'signature.txt','a')asf:try:f.write(i)除了:pass#Sex=re.findall("'Sex':(.*?),",all_friends)man=woman=other=0foriinSex:ifi=='1':man+=1elifi=='2':woman+=1else:other+=1#省市数据shengfens=re.findall(r"'Province':'(.*?)',",all_friends)chengshis=re.findall(r"'City':'(.*?)',",all_friends)#绘制好友省份分布图shengfen=[]foriinrange(len(shengfens)):ifshengfens[i]=='':passelse:shengfen.append(shengfens[i])#绘制河南省友人分布图chengshi=[]foriinrange(len(chengshis)):ifshengfens[i]=='Henan':chengshi.append(chengshis[i])02可视化展示一共得到了973个好友的数据。让我们可视化下面的数据。01签名词云可视化通过对所有朋友个人签名的词云进行可视化,我们发现努力、生活、时间、世界、一无所有是最常见的词。似乎大多数朋友都倾向于和这些词有关。代码如下:withopen("signature.txt",)asf:job_title_1=f.read()job_title_2=re.sub('span','',job_title_1)job_title_3=re.sub('class','',job_title_2)job_title_4=re.sub('表情符号','',job_title_3)job_title_5=re.sub('我自己','',job_title_4)job_title_6=re.sub('回复','',job_title_5)#job_title_7=re.sub('at','',job_title_6)contents_cut_job_title=jieba.cut(job_title_6)contents_list_job_title="".join(contents_cut_job_title)wc=WordCloud(stopwords=STOPWORDS.add("one"),搭配=False,background_color="white",font_path=r"K:\苏新石刘开剑.ttf",width=400,height=300,random_state=42,mask=imread('xin.jpg',pilmode="RGB"))wc.generate(contents_list_job_title)wc.to_file("recommendation.png")02性别数量图表通过可视化好友性别,发现我们有543位男性好友,318位女性好友,还有112人没有填写在这些信息中。03省份分布图通过对这973位好友所在省份的可视化展示,我们发现好友最多的集中在河南,有263位,其次是广东,有69位。河南的好友最多,可能是因为志斌来自河南。代码如下:province_distribution=dict(Counter(shengfen).most_common())provice=list(province_distribution.keys())values=list(province_distribution.values())map=Map("中国地图",width=1200,height=600)map.add("",provice,values,visual_range=[0,200],maptype='china',is_visualmap=True,visual_text_color='#000',is_label_show=True)map.render(path="Map.html")04河南省好友分布通过上面的分析,我们发现我们在河南的好友最多,于是我再可视化一下我在河南省的好友分布,按地市.从展示图片中我们发现,最多的朋友集中在郑州,有116人,其次是鹤壁,有38人。我家是鹤壁人,在郑州上学。郑州的朋友比鹤壁多。原因。代码如下:city=[]values=[]fork,vindict(Counter(chengshi).most_common()).items():city.append(k+'city')values.append(v)map2=Map("河南地图",'河南',width=1200,height=600)map2.add('河南',city,values,visual_range=[1,25],maptype='河南',is_visualmap=True,visual_text_color='#000')map2.render(path="河南地图.html")