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 读取 Excel 数据

《如何使用Python读取Excel数据》:本文主要介绍使用Python读取Excel数据的详细教程,通过pandas和openpyxl,你可以轻松读取Excel文件,并进行各种数据处理操... 目录使用 python 读取 Excel 数据的详细教程1. 安装必要的依赖2. 读取 Excel 文件3. 读

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指

利用Python调试串口的示例代码

《利用Python调试串口的示例代码》在嵌入式开发、物联网设备调试过程中,串口通信是最基础的调试手段本文将带你用Python+ttkbootstrap打造一款高颜值、多功能的串口调试助手,需要的可以了... 目录概述:为什么需要专业的串口调试工具项目架构设计1.1 技术栈选型1.2 关键类说明1.3 线程模

Python ZIP文件操作技巧详解

《PythonZIP文件操作技巧详解》在数据处理和系统开发中,ZIP文件操作是开发者必须掌握的核心技能,Python标准库提供的zipfile模块以简洁的API和跨平台特性,成为处理ZIP文件的首选... 目录一、ZIP文件操作基础三板斧1.1 创建压缩包1.2 解压操作1.3 文件遍历与信息获取二、进阶技

Python Transformers库(NLP处理库)案例代码讲解

《PythonTransformers库(NLP处理库)案例代码讲解》本文介绍transformers库的全面讲解,包含基础知识、高级用法、案例代码及学习路径,内容经过组织,适合不同阶段的学习者,对... 目录一、基础知识1. Transformers 库简介2. 安装与环境配置3. 快速上手示例二、核心模

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中

Python使用getopt处理命令行参数示例解析(最佳实践)

《Python使用getopt处理命令行参数示例解析(最佳实践)》getopt模块是Python标准库中一个简单但强大的命令行参数处理工具,它特别适合那些需要快速实现基本命令行参数解析的场景,或者需要... 目录为什么需要处理命令行参数?getopt模块基础实际应用示例与其他参数处理方式的比较常见问http

python实现svg图片转换为png和gif

《python实现svg图片转换为png和gif》这篇文章主要为大家详细介绍了python如何实现将svg图片格式转换为png和gif,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录python实现svg图片转换为png和gifpython实现图片格式之间的相互转换延展:基于Py

Python中的getopt模块用法小结

《Python中的getopt模块用法小结》getopt.getopt()函数是Python中用于解析命令行参数的标准库函数,该函数可以从命令行中提取选项和参数,并对它们进行处理,本文详细介绍了Pyt... 目录getopt模块介绍getopt.getopt函数的介绍getopt模块的常用用法getopt模

Python利用ElementTree实现快速解析XML文件

《Python利用ElementTree实现快速解析XML文件》ElementTree是Python标准库的一部分,而且是Python标准库中用于解析和操作XML数据的模块,下面小编就来和大家详细讲讲... 目录一、XML文件解析到底有多重要二、ElementTree快速入门1. 加载XML的两种方式2.