Python数据分析之微信好友数据分析

2023-11-02 05:59

本文主要是介绍Python数据分析之微信好友数据分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

基于微信开放的个人号接口python库itchat,实现对微信好友的获取,并对省份、性别、微信签名做数据分析。

效果:




直接上代码,建三个空文本文件stopwords.txt,newdit.txt、unionWords.txt,下载字体simhei.ttf或删除字体要求的代码,就可以直接运行。

 #wxfriends.py  2018-07-09
import itchat
import sys
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']#绘图时可以显示中文
plt.rcParams['axes.unicode_minus']=False#绘图时可以显示中文
import jieba
import jieba.posseg as pseg
from scipy.misc import imread
from wordcloud import WordCloud
from os import path
#解决编码问题
non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)#获取好友信息
def getFriends():friends = itchat.get_friends(update=True)[0:]flists = []for i in friends:fdict={}fdict['NickName']=i['NickName'].translate(non_bmp_map)if i['Sex'] == 1:fdict['Sex']='男'elif i['Sex'] == 2:fdict['Sex']='女'else:fdict['Sex']='雌雄同体'if i['Province'] == '':fdict['Province'] ='未知'else:fdict['Province']=i['Province']fdict['City']=i['City']fdict['Signature']=i['Signature']flists.append(fdict)return flists#将好友信息保存成CSV
def saveCSV(lists):df = pd.DataFrame(lists)try:df.to_csv("wxfriends.csv",index = True,encoding='gb18030')except Exception as ret:print(ret)return df#统计性别、省份字段    
def anysys(df):df_sex = pd.DataFrame(df['Sex'].value_counts())df_province = pd.DataFrame(df['Province'].value_counts()[:15])df_signature = pd.DataFrame(df['Signature'])return df_sex,df_province,df_signature#绘制柱状图,并保存   
def draw_chart(df_list,x_feature):try:x = list(df_list.index)ylist = df_list.valuesy = []for i in ylist :for j in i:y.append(j)plt.bar(x,y,label=x_feature)plt.legend()plt.savefig(x_feature)plt.close()except:print("绘图失败")#解析取个性签名构成列表     
def getSignList(signature):sig_list = []for i in signature.values:for j in i:sig_list.append(j.translate(non_bmp_map))return sig_list#分词处理,并根据需要填写停用词、自定义词、合并词替换
def segmentWords(txtlist):stop_words = set(line.strip() for line in open('stopwords.txt', encoding='utf-8'))newslist = []#新增自定义词jieba.load_userdict("newdit.txt")for subject in txtlist:if subject.isspace():continueword_list = pseg.cut(subject)for word, flag in word_list:if not word in stop_words and flag == 'n' or flag == 'eng' and word !='span' and word !='class':newslist.append(word)#合并指定的相似词for line in open('unionWords.txt', encoding='utf-8'):newline = line.encode('utf-8').decode('utf-8-sig')    #解决\ufeff问题unionlist = newline.split("*")for j in range(1,len(unionlist)):#wordDict[unionlist[0]] += wordDict.pop(unionlist[j],0)for index,value in enumerate(newslist):if value == unionlist[j]:newslist[index] = unionlist[0]  return newslist#高频词统计
def countWords(newslist):wordDict = {}for item in newslist:wordDict[item] = wordDict.get(item,0) + 1itemList = list(wordDict.items())itemList.sort(key=lambda x:x[1],reverse=True)        for i in range(100):word, count = itemList[i]print("{}:{}".format(word,count))#绘制词云
def drawPlant(newslist):d = path.dirname(__file__)mask_image = imread(path.join(d, "timg.png"))content = ' '.join(newslist)wordcloud = WordCloud(font_path='simhei.ttf', background_color="white",width=1300,height=620, max_words=200).generate(content)   #mask=mask_image,# Display the generated image:plt.imshow(wordcloud)plt.axis("off")wordcloud.to_file('wordcloud.jpg')plt.show()def main():#登陆微信itchat.auto_login()   # 登陆后不需要扫码   hotReload=Trueflists = getFriends()fdf = saveCSV(flists)df_sex,df_province,df_signature = anysys(fdf)draw_chart(df_sex,"性别")draw_chart(df_province,"省份")wordList = segmentWords(getSignList(df_signature))countWords(wordList)drawPlant(wordList)main()

这篇关于Python数据分析之微信好友数据分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/328588

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以