利用python深度分析微信朋友圈好友

最近看了wxpy這個包,感覺還不錯,分析一下微信的好友。

分析的目的:

1.看看好友的性別占比、地域分布

2.分析好友的個性簽名

3.對好友的簽名進行情感分析

環(huán)境:python 3.6

需要的包wxpy、jieba、snownlp、scipy、wordcloud(這個pip可能直接安裝不了,會提示需要c++之類的錯誤,直接去官網(wǎng)下載whl文件,用pip離線安裝就好了,命令:pip install D:/xxxx/xxxx/xxx.whl把xxx換成你的文件路徑)

過程如下:

先導(dǎo)入需要的所有包。利用wxpy的bot()接口,可以獲得好友、公眾號、群聊等屬性,可以完成大部分web端微信的操作,比如自己跟自己聊天,添加好友等。


from wxpy import *

from snownlp import SnowNLP,sentiment

import re,jieba

from scipy.misc import imread

from wordcloud import WordCloud, ImageColorGenerator,STOPWORDS

import matplotlib.pyplot as plt

from collections import Counter

bot=Bot()

friends=bot.friends()#獲得好友對象

groups=bot.groups()#獲得群聊對象

mps=bot.mps()#獲得微信公眾號

print(mps)

#計算男女性別,畫出餅圖

sex_dict={'boy':0,'girl':0,'other':0}

for friend in friends:

    if friend.sex==1:

        sex_dict['boy']+=1

    elif friend.sex==2:

        sex_dict['girl']+=1

    else:

        sex_dict['other']+=1

print('有男生{}個,女生{}個,未知性別{}個'.format(sex_dict['boy'],sex_dict['girl'],sex_dict['other']))

labels = ['boy','girl','other']

colors = ['red','yellow','green']

explode = (0.1, 0, 0)  #最大的突出顯示

plt.figure(figsize=(8,5), dpi=80)

plt.axes(aspect=1)

plt.pie(sex_dict.values(),explode=explode,labels=labels, autopct='%1.2f%%',colors=colors,labeldistance = 1.1, shadow = True, startangle = 90, pctdistance = 0.6)

plt.title("SEX ANALYSIS",bbox=dict(facecolor='g', edgecolor='blue', alpha=0.65 ))#設(shè)置標題和標題邊框

plt.savefig("sex_analysis.jpg")

plt.show()

運行過程中,會彈出二維碼,微信掃描登錄一下就可以看到下面的圖片了。

image

我的好友男女平均分配,不知道其他人的怎么樣。

接下來看好友的地域分布


city=[]

Municipality=['上海','上海市','北京','北京市','重慶','重慶市','天津','天津市']

for friend in friends:

    if friend.province  in Municipality:

        city.append(friend.province)#直轄市直接添加城市

    else:

        city.append(friend.city)

#print(city.count('上海'))

counts=dict(Counter(city))#統(tǒng)計各個地區(qū)人數(shù)

print(counts)

df=pd.DataFrame([counts]).T#轉(zhuǎn)成DataFrame方便保存和后面畫圖,裝置成豎排形式

看地理圖,就要請出大名鼎鼎的tableau,一鍵生成,用matplotlib也可以畫地理圖,比較麻煩一些而已。

image

地理圖可以很清晰看到好友分布地域和數(shù)量。

接下來進行好友簽名分析和情感分析

text1=[]

emotions=[]

for friend in friends:

    sig=friend.signature.strip()

    newsig=re.sub(re.compile('<.*?>|[0-9]|。|,|!|~|—|”|“|《|》|\?|、|:'), '', sig)#去掉數(shù)字標點符號

    text1.append(newsig)

    if len(newsig)>0:

        sentiments = SnowNLP(newsig).sentiments

        emotions.append(sentiments)

text = "".join(text1)

wordlist=" ".join(jieba.cut(text,cut_all=True))#結(jié)巴分詞,用空格連接

stopwords = STOPWORDS#設(shè)置停用詞

bgimg=imread(r'C:\Users\lbship\Desktop\mice.jpg')#設(shè)置背景圖片

font_path=r'C:\Windows\Fonts\simkai.ttf'

wc = WordCloud(font_path=font_path,  # 設(shè)置字體

              background_color="white",  # 背景顏色

              max_words=2000,  # 詞云顯示的最大詞數(shù)

              stopwords = stopwords,        # 設(shè)置停用詞

              mask=bgimg,  # 設(shè)置背景圖片

              max_font_size=100,  # 字體最大值

              random_state=42,#設(shè)置有多少種隨機生成狀態(tài),即有多少種配色

              width=1000, height=860, margin=2,# 設(shè)置圖片默認的大小,margin為詞語邊緣距離

              ).generate(wordlist)

image_colors = ImageColorGenerator(bgimg)#根據(jù)圖片生成詞云顏色

plt.imshow(wc)

plt.axis("off")#不顯示坐標尺寸

plt.savefig("sig.jpg")

plt.show()

#情感分析

positive=len(list(i for i in emotions if i>0.66))

normal=len(list(i for i in emotions if i<=0.66 and i>=0.33))

#normal = len(list(filter(lambda x:x>=0.33 and x<=0.66,emotions)))

negative=len(list(i for i in emotions if i<0.33))

labels = ['POSITIVE','NORMAL','NEGATIVE']

values = (positive,normal,negative)

plt.rcParams['font.sans-serif'] = ['simHei']

plt.rcParams['axes.unicode_minus'] = False

plt.title("SENTIMENTS ANALYSIS",fontsize='large',fontweight='bold',bbox=dict(facecolor='blue', edgecolor='yellow', alpha=0.5 ))

plt.xlabel('sentiments analysis')

plt.ylabel('counts')

plt.xticks(range(3),labels)

plt.bar(range(3), values, color = 'rgb')

plt.savefig("sentiment.jpg")

plt.show()
image
image

朋友圈還是積極向上的朋友比較多。

下面是完整代碼


from wxpy import *

from snownlp import SnowNLP,sentiment

import re,jieba

import pandas as pd

from scipy.misc import imread

from wordcloud import WordCloud, ImageColorGenerator,STOPWORDS

import matplotlib.pyplot as plt

from collections import Counter

bot=Bot()

friends=bot.friends()#獲得好友對象

groups=bot.groups()#獲得群聊對象

mps=bot.mps()#獲得微信公眾號

print(mps)

#計算男女性別,畫出餅圖

sex_dict={'boy':0,'girl':0,'other':0}

for friend in friends:

    if friend.sex==1:

        sex_dict['boy']+=1

    elif friend.sex==2:

        sex_dict['girl']+=1

    else:

        sex_dict['other']+=1

print('有男生{}個,女生{}個,未知性別{}個'.format(sex_dict['boy'],sex_dict['girl'],sex_dict['other']))

labels = ['boy','girl','other']

colors = ['red','yellow','green']

explode = (0.1, 0, 0)  #最大的突出顯示

plt.figure(figsize=(8,5), dpi=80)

plt.axes(aspect=1)

plt.pie(sex_dict.values(),explode=explode,labels=labels, autopct='%1.2f%%',colors=colors,labeldistance = 1.1, shadow = True, startangle = 90, pctdistance = 0.6)

plt.title("SEX ANALYSIS",bbox=dict(facecolor='g', edgecolor='blue', alpha=0.65 ))#設(shè)置標題和標題邊框

plt.savefig("sex_analysis.jpg")

plt.show()

#獲取城市分布

city=[]

Municipality=['上海','上海市','北京','北京市','重慶','重慶市','天津','天津市']

for friend in friends:

    if friend.province  in Municipality:

        city.append(friend.province)#直轄市直接添加城市

    else:

        city.append(friend.city)

#print(city.count('上海'))

counts=dict(Counter(city))#統(tǒng)計各個地區(qū)人數(shù)

print(counts)

df=pd.DataFrame([counts]).T#轉(zhuǎn)成DataFrame方便保存和后面畫圖,裝置成豎排形式

df.to_excel('city.xlsx')

#獲取好友簽名,生成詞云,并進行情感分析

text1=[]

emotions=[]

for friend in friends:

    sig=friend.signature.strip()

    newsig=re.sub(re.compile('<.*?>|[0-9]|。|,|!|~|—|”|“|《|》|\?|、|:'), '', sig)#去掉數(shù)字標點符號

    text1.append(newsig)

    if len(newsig)>0:

        sentiments = SnowNLP(newsig).sentiments

        emotions.append(sentiments)

text = "".join(text1)

wordlist=" ".join(jieba.cut(text,cut_all=True))#結(jié)巴分詞,用空格連接

stopwords = STOPWORDS#設(shè)置停用詞

bgimg=imread(r'C:\Users\lbship\Desktop\mice.jpg')#設(shè)置背景圖片

font_path=r'C:\Windows\Fonts\simkai.ttf'

wc = WordCloud(font_path=font_path,  # 設(shè)置字體

              background_color="white",  # 背景顏色

              max_words=2000,  # 詞云顯示的最大詞數(shù)

              stopwords = stopwords,        # 設(shè)置停用詞

              mask=bgimg,  # 設(shè)置背景圖片

              max_font_size=100,  # 字體最大值

              random_state=42,#設(shè)置有多少種隨機生成狀態(tài),即有多少種配色

              width=1000, height=860, margin=2,# 設(shè)置圖片默認的大小,margin為詞語邊緣距離

              ).generate(wordlist)

image_colors = ImageColorGenerator(bgimg)#根據(jù)圖片生成詞云顏色

plt.imshow(wc)

plt.axis("off")#不顯示坐標尺寸

plt.savefig("sig.jpg")

plt.show()

#情感分析

positive=len(list(i for i in emotions if i>0.66))

normal=len(list(i for i in emotions if i<=0.66 and i>=0.33))

#normal = len(list(filter(lambda x:x>=0.33 and x<=0.66,emotions)))

negative=len(list(i for i in emotions if i<0.33))

labels = ['POSITIVE','NORMAL','NEGATIVE']

values = (positive,normal,negative)

plt.rcParams['font.sans-serif'] = ['simHei']

plt.rcParams['axes.unicode_minus'] = False

plt.title("SENTIMENTS ANALYSIS",fontsize='large',fontweight='bold',bbox=dict(facecolor='blue', edgecolor='yellow', alpha=0.5 ))

plt.xlabel('sentiments analysis')

plt.ylabel('counts')

plt.xticks(range(3),labels)

plt.bar(range(3), values, color = 'rgb')

plt.savefig("sentiment.jpg")

plt.show()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容