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

关于微信好友数据分析

时间:2023-03-26 14:20:36 Python

@font-face{font-family:"TimesNewRoman";}@font-face{字体系列:“Calibri”;}@font-face{font-family:"Calibri";}p.MsoNormal{mso-style-name:text;mso-style-parent:"";保证金:0pt;保证金底部:.0001pt;mso-分页:无;文本对齐:对齐;文字对齐:表意文字间;字体系列:Calibri;mso-fareast-font-family:Arial;mso-bidi-font-family:'TimesNewRoman';字体大小:10.5000pt;mso-字体字距:1.0000pt;}span.msoIns{mso-style-type:export-only;mso样式名称:"";文字修饰:下划线;文本下划线:单个;颜色:蓝色;}span.msoDel{mso-style-type:export-only;mso样式名称:"";文本装饰:直通;红色;}@page{mso-page-border-surround-header:no;mso-page-border-surround-footer:no;}@pageSection0{margin-top:72.0000pt;保证金底部:72.0000pt;左边距:90.0000pt;右边距:90.0000pt;;}div.Section0{page:Section0;}背景与研究现状在我国互联网的发展过程中,PC互联网日趋饱和,但移动互联网正在显现井喷式发展数据显示,截至2013年底,中国手机网民规模突破5亿,占比81%。随着移动终端价格的下降和wifi的广泛部署,移动互联网用户呈爆发式增长。微信已经成为连接线上与线下、虚拟与现实、消费与产业的重要工具,提升了O2O营销用户的转化率。过去开发软件时,程序员往往要考虑不同开发环境的语言、设备适配性和成本。现在,开发者可以在一个“类操作底层”上开发应用,打破了以往开发环境受限的局面。2研究意义与目的随着宽带无线接入技术和移动终端技术的飞速发展,人们渴望随时随地甚至在移动中从互联网上获取信息和服务。发展。然而,移动互联网在移动终端、接入网络、应用服务、安全和隐私保护等方面仍面临一系列挑战。对其基础理论和关键技术的研究对于国家信息产业的全面发展具有重要的现实意义。3.研究内容及数据获取普通用户用手机扫描二维码并在手机上确认,wxpy自动从用户网页版微信中获取好友列表,包括好友的昵称、所在地、签名、性别和其他信息。Python程序设计微信好友特征数据分析及可视化#1.导入包操作fromwxpyimport*importreimportjiebaimportnumpyasnpfromscipy.miscimportimreadfromwordcloudimportWordCloudimportmatplotlib.pyplotaspltfrompylabimportmplimportpandasaspdmpl.rcParams['font.sans-serif']=['SimHei']frompyecharts.chartsimportMapfrompyechartsimportoptionsasopts#2.登录操作bot=Bot()#列出登录账号的所有好友all_friends=bot.friends()print(all_friends)#获取登录账号关注的所有公众号all_maps。群聊列表",all_groups)#根据评论名搜索好友myfriend=bot.friends().search('徐宽')[0]print("搜索好友:",myfriend)#搜索好友和sendmessages#bot.friends().search('XuKuan')[0].send('Hello')#发送信息给文件传输助手bot.file_helper.send("hello")#3.显示比例男性到女性sex_dict={'male':0,'female':0,"no_set":0}forfriendinall_friends:print(friend,friend.sex)iffriend.sex==1:sex_dict['male']+=1eliffriend.sex==2:sex_dict['female']+=1eliffriend.sex==0:sex_dict['no_set']+=1print(sex_dict)#4使用matplotlib可视化切片=[sex_dict["male"],sex_dict["female"],sex_dict["no_set"]]activities=["male","female","no_set"]cols=["r","m","g"]#startangle:开始绘制的角度,逆时针旋转#shadow:阴影#%1.1f%%:格式字符串,integerPartialminimum1digit,小数点后一位,%%:escapecharacterplt.pie(slices,labels=activities,colors=cols,startangle=90,shadow=True,autopct='%1.1f%%')plt.title("WeChatfriendproportionmap")plt.savefig("WeChat_sex.png")#统计好友登录的省份数province_dict={'河北':0,'山东':0,'辽宁':0、'广西':0、'吉林':0、'甘肃':0、'青海':0、'河南':0、'江苏':0、'湖南':0、'江西':0,'浙江':0,'广东':0,'云南':0,'福建':0,'台湾':0,'海南':0,'山西':0,'四川':0,'陕西':0,'贵州':0,'安徽':0,'北京':0,'天津':0,'重庆':0,'上海':0,'香港':0,'澳门':0,'新疆':0,'内蒙古':0,'西藏':0,'黑龙江':0,'宁夏':0}#all_friends中friend的统计省份:#print(friend.province)iffriend.provinceinprovince_dict.keys():province_dict[friend.province]+=1print("province_dict")print(province_dict)#为了方便数据呈现,生成JSONArray格式的数据data=[]forkey,valueinprovince_dict.items():data.append({'name':key,'value':value})#在数据列表末尾添加一个函数(){//XMbrokerapplicationhttp://www.fx61.com/brokerlist/xm.htmlprint(数据)data_process=pd.DataFrame(data)#创建数据框data_process.columns=['city','popu']print(data_process)map=Map().add("微信好友城市分布图",[list(z)forzinzip(data_process['city'],data_process['popu'])],"china").set_global_opts(title_opts=opts.TitleOpts(title="Map-VisualMap(连续型)"),visualmap_opts=opts.VisualMapOpts(max_=10))map.render('map.html')#在with...as...语句的最后,自动调用f.close()#ameans:appenddefwrite_txt_file(path,txt)attheendofthefile:#Writefilewithopen(path,'a',encoding='gbk')asf:returnf.write(txt)#每次运行程序前,需要删除最后一个文件#默认字符编码为GBKdefread_txt_file(path):withopen(path,'r',encoding='gbk')asf:returnf.read()#统计登录账号好友签名为friendinall_ffriends:print(friend,friend.signature)#清理数据,去除标点符号等影响词频统计的因素#[...]:匹配括号内任意字符#r:防止转义pattern=re.compile(r'[一-龥]+')#将正则字符串编译成正则表达式对象,在后面的匹配中重复使用#匹配某个签名,只匹配汉字,结果是一个列表filterdata=re.findall(pattern,friend.signature)print(filterdata)write_txt_file('signatures.txt',''.join(filterdata))#读取文件并输出content=read_txt_file('signatures.txt')print(content)#输出内容,只有汉字#输出分词结果,结果是列表segment=jieba.lcut(content)#精确模式:没有冗余数据,适合textanalysisprint(segment)#生成一列元素的数据框word_df=pd.DataFrame({'segment':segment})#字典类型print(word_df)#index_col=False:第一行不作为index#seq="":Separator#names=['stopword']:列名#"stopwords.txt":停用词库stopwords=pd.read_csv("stopwords.txt",index_col=False,sep="",names=['stopword'],encoding='gbk')print(stopwords)#查看过滤停用词后的数据框word_df=word_df[~word_df.segment.isin(stopwords.stopword)]print("过滤后:")print(word_df)#检查分词的词频#python中的groupby可以看作是基于行或基于索引的聚合操作#agg函数提供了基于列的聚合操作,一般与groupby结合使用#np.size:统计numpy库中某列不同值的个数_stat=word_df.groupby(by=['segment'])['segment'].agg({"count":np.size})#警告信息print(words_stat)#根据count列降序排列words_statwords_stat=words_stat.reset_index().sort_values(by=["count"],ascending=False)print(words_stat)#读取背景图片color_mask=imread("black_mask.png")#设置词云属性wordcloud=WordCloud(font_path="Hiragino.ttf",#设置字体background_color="Pink",#设置颜色max_words=100,#bbbMask=color_mask,#设置背景图片max_font_size=100#字体最大值)#百字word_frequency={x[0]:x[1]forxinwords_stat.head(100).values}print(word_frequency)#绘制词云图wordcloud.generate_from_frequencies(word_frequency)wordcloud.to_file("wordcloud.png")#处理图像plt.imshow(wordcloud)plt.axis("off")#隐藏坐标轴plt.show()