用Python爬了我的微信好友,他們是這樣的...

itchat:微信網(wǎng)頁版接口封裝Python版本,在本文中用以獲取微信好友信息。 jieba:結(jié)巴分詞的 Python 版本,在本文中用以對文本信息進(jìn)行分詞處理。 matplotlib:Python 中圖表繪制模塊,在本文中用以繪制柱形圖和餅圖 snownlp:一個(gè) Python 中的中文分詞模塊,在本文中用以對文本信息進(jìn)行情感判斷。 PIL:Python 中的圖像處理模塊,在本文中用以對圖片進(jìn)行處理。 numpy:Python中 的數(shù)值計(jì)算模塊,在本文中配合 wordcloud 模塊使用。 wordcloud:Python 中的詞云模塊,在本文中用以繪制詞云圖片。 TencentYoutuyun:騰訊優(yōu)圖提供的 Python 版本 SDK ,在本文中用以識別人臉及提取圖片標(biāo)簽信息。
01
數(shù)據(jù)分析
itchat.auto_login(hotReload = True)friends = itchat.get_friends(update = True)

02
好友性別
def analyseSex(firends):sexs = list(map(lambda x:x['Sex'],friends[1:]))counts = list(map(lambda x:x[1],Counter(sexs).items()))labels = ['Unknow','Male','Female']colors = ['red','yellowgreen','lightskyblue']plt.figure(figsize=(8,5), dpi=80)plt.axes(aspect=1)plt.pie(counts, #性別統(tǒng)計(jì)結(jié)果labels=labels, #性別展示標(biāo)簽colors=colors, #餅圖區(qū)域配色labeldistance = 1.1, #標(biāo)簽距離圓點(diǎn)距離autopct = '%3.1f%%', #餅圖區(qū)域文本格式shadow = False, #餅圖是否顯示陰影startangle = 90, #餅圖起始角度pctdistance = 0.6 #餅圖區(qū)域文本距離圓點(diǎn)距離)plt.legend(loc='upper right',)plt.title(u'%s的微信好友性別組成' % friends[0]['NickName'])plt.show()

03
好友頭像
def analyseHeadImage(frineds):# Init PathbasePath = os.path.abspath('.')baseFolder = basePath + '\\HeadImages\\'if(os.path.exists(baseFolder) == False):os.makedirs(baseFolder)# Analyse ImagesfaceApi = FaceAPI()use_face = 0not_use_face = 0image_tags = ''for index in range(1,len(friends)):friend = friends[index]# Save HeadImagesimgFile = baseFolder + '\\Image%s.jpg' % str(index)imgData = itchat.get_head_img(userName = friend['UserName'])if(os.path.exists(imgFile) == False):with open(imgFile,'wb') as file:file.write(imgData)# Detect Facestime.sleep(1)result = faceApi.detectFace(imgFile)if result == True:use_face += 1else:not_use_face += 1# Extract Tagsresult = faceApi.extractTags(imgFile)image_tags += ','.join(list(map(lambda x:x['tag_name'],result)))labels = [u'使用人臉頭像',u'不使用人臉頭像']counts = [use_face,not_use_face]colors = ['red','yellowgreen','lightskyblue']plt.figure(figsize=(8,5), dpi=80)plt.axes(aspect=1)plt.pie(counts, #性別統(tǒng)計(jì)結(jié)果labels=labels, #性別展示標(biāo)簽colors=colors, #餅圖區(qū)域配色labeldistance = 1.1, #標(biāo)簽距離圓點(diǎn)距離autopct = '%3.1f%%', #餅圖區(qū)域文本格式shadow = False, #餅圖是否顯示陰影startangle = 90, #餅圖起始角度pctdistance = 0.6 #餅圖區(qū)域文本距離圓點(diǎn)距離)plt.legend(loc='upper right',)plt.title(u'%s的微信好友使用人臉頭像情況' % friends[0]['NickName'])plt.show()image_tags = image_tags.encode('iso8859-1').decode('utf-8')back_coloring = np.array(Image.open('face.jpg'))wordcloud = WordCloud(font_path='simfang.ttf',background_color="white",max_words=1200,mask=back_coloring,max_font_size=75,random_state=45,width=800,height=480,margin=15)wordcloud.generate(image_tags)plt.imshow(wordcloud)plt.axis("off")plt.show()


04
好友簽名
def analyseSignature(friends):signatures = ''emotions = []pattern = re.compile("1f\d.+")for friend in friends:signature = friend['Signature']if(signature != None):signature = signature.strip().replace('span', '').replace('class', '').replace('emoji', '')signature = re.sub(r'1f(\d.+)','',signature)if(len(signature)>0):nlp = SnowNLP(signature)emotions.append(nlp.sentiments)signatures += ' '.join(jieba.analyse.extract_tags(signature,5))with open('signatures.txt','wt',encoding='utf-8') as file:file.write(signatures)# Sinature WordCloudback_coloring = np.array(Image.open('flower.jpg'))wordcloud = WordCloud(font_path='simfang.ttf',background_color="white",max_words=1200,mask=back_coloring,max_font_size=75,random_state=45,width=960,height=720,margin=15)wordcloud.generate(signatures)plt.imshow(wordcloud)plt.axis("off")plt.show()wordcloud.to_file('signatures.jpg')# Signature Emotional Judgmentcount_good = len(list(filter(lambda x:x>0.66,emotions)))count_normal = len(list(filter(lambda x:x>=0.33 and x<=0.66,emotions)))count_bad = len(list(filter(lambda x:x<0.33,emotions)))labels = [u'負(fù)面消極',u'中性',u'正面積極']values = (count_bad,count_normal,count_good)plt.rcParams['font.sans-serif'] = ['simHei']plt.rcParams['axes.unicode_minus'] = Falseplt.xlabel(u'情感判斷')plt.ylabel(u'頻數(shù)')plt.xticks(range(3),labels)plt.legend(loc='upper right',)plt.bar(range(3), values, color = 'rgb')plt.title(u'%s的微信好友簽名信息情感分析' % friends[0]['NickName'])plt.show()


05
好友位置
def analyseLocation(friends):headers = ['NickName','Province','City']with open('location.csv','w',encoding='utf-8',newline='',) as csvFile:writer = csv.DictWriter(csvFile, headers)writer.writeheader()for friend in friends[1:]:row = {}row['NickName'] = friend['NickName']row['Province'] = friend['Province']row['City'] = friend['City']writer.writerow(row)

06
總結(jié)
(版權(quán)歸原作者所有,侵刪)
![]()

點(diǎn)擊下方“閱讀原文”查看更多
評論
圖片
表情
