我通過Python對自己的微信朋友圈進行了可視化分析得到了意想不到的答案

在這裏插入圖片描述

前提準備

確保安裝用到的模塊和庫:

itchat
pyecharts
jieba
wordcloud 
collections
PIL

第一步獲取朋友圈好友的數據

import itchat
# 獲取數據
def get_data():
    itchat.auto_login()
    friends = itchat.get_friends(update=True)  # 返回一個包含用戶信息字典的列表
    return friends

第二步處理數據,並存儲到txt文件中

# 處理數據
def parse_data(data):
    friends = []
    for item in data[1:]:  # 因爲第一個元素是自己的信息,去掉
        friend = {
            'NickName': item['NickName'],  # 暱稱
            'RemarkName': item['RemarkName'],  # 備註名
            'Sex': item['Sex'],  # 性別:1男,2女,0未設置
            'Province': item['Province'],  # 省份
            'City': item['City'],  # 城市
            'Signature': item['Signature'].replace('\n', ' ').replace(',', ' '),  # 個性簽名(處理簽名內容換行的情況)
           }
        #print(friend)
        friends.append(friend)
    return friends
# 存儲數據,存儲到txt文件
def save_to_txt():
    friends = parse_data(get_data())
    for item in friends:
        with open('friends.txt', mode='a', encoding='utf-8') as f:
            f.write('%s,%s,%d,%s,%s,%s\n' % ( item['NickName'], item['RemarkName'], item['Sex'], item['Province'], item['City'], item['Signature'],))

第三步開始分析,走起!

3.1 分析朋友圈sex

通過分析我得知我的交際圈被male佔領了,怪不得我還沒有女朋友呢!不過也不完全對,畢竟我是計算機專業的,男女比例也達到了驚人的8:1,哎,遙遙無期啊,距離脫單。想起個段子,程序猿沒有對象,可以 new 一個對象出來,哈哈!!!在這裏插入圖片描述
看一下實現代碼:

from pyecharts import Pie
def stastic_sex():
    # 獲取所有性別
    sex = []
    with open('friends.txt', mode='r', encoding='utf-8') as f:
        rows = f.readlines()
        for row in rows:
            print(row.split(',')[2])
            sex.append(row.split(',')[2])

    # 統計每個性別的數量
    attr = ['帥哥', '美女', '未知']
    value = [sex.count('1'), sex.count('2'), sex.count('0')]

    pie = Pie('好友性別比例', '好友總人數:%d' % len(sex), title_pos='center')
    pie.add('', attr, value, radius=[30, 75], rosetype='area', is_label_show=True,
            is_legend_show=True, legend_top='bottom',is_more_utils=True)
    # pie.show_config()
    pie.render('好友性別比例.html')

3.2 分析好友暱稱,看看起名都有什麼個操作

在這裏插入圖片描述
好吧,朋友圈裏老師挺多的,這個情有可原,但是這個什麼明天是神馬,都趕着明天集市嗎,哈哈,又看了看其他的,嗯,我好友裏面還算乾淨些,沒什麼牛逼哄哄的稱號哈。想想自己的名字,嗯是不是該趕着潮流了~~~~~~

代碼實現:

#utf-8

import jieba
from wordcloud import WordCloud

# 獲取全部的名字
NickNames = []
with open('friends.txt', 'r', encoding='utf-8') as f:
    rows = f.readlines()
    for row in rows:
        NickName = row.split(',')[0]
        if NickName != '':
            # print(City)
            NickNames.append(NickName)
# 設置分詞 False精準模式分詞、True全模式分詞
split = jieba.cut(str(NickNames), cut_all=False)
words = ' '.join(split)  # 以空格進行拼接
# print(words)
# WordCloud()函數的詞雲參數分別表示:畫布寬高、背景顏色、背景圖形狀、字體、屏蔽詞、最大詞的字體大小
wc = WordCloud(width=1024, height=768, background_color='white',  font_path='STKAITI.TTF',max_font_size=400, random_state=50)
# 將分詞後數據傳入雲圖
wc.generate_from_text(words)
wc.to_file('好友暱稱詞雲.jpg')

3.3分析哪裏來的

在這裏插入圖片描述
我不看不知道,一看嚇一跳。這我以後嗯,可以放心了,勞資是的東北大漢,旁邊兄弟那統統都是你愁啥,瞅你咋地,再瞅個試試,試試就試試,的,嗯,不錯。不過最後我突然想起個段子,不知道當講不當講,反正笑笑是可以的:孩子的爸身體缸缸的,就是沒有文化,沒給幾個孩子起名字,就按大小順序管孩子叫大鱉犢子、二鱉犢子……。
哈哈哈。
話不多說,進入正題還是,看一下實現代碼:

import jieba
from wordcloud import WordCloud

# 獲取全部的省份名
Provinces = []
with open('friends.txt', 'r', encoding='utf-8') as f:
    rows = f.readlines()
    for row in rows:
        Province = row.split(',')[3]
        if Province != '':
            # print(City)
           Provinces.append(Province)
# 設置分詞 False精準模式分詞、True全模式分詞
split = jieba.cut(str(Provinces), cut_all=False)
words = ' '.join(split)  # 以空格進行拼接
# print(words)
# WordCloud()函數的詞雲參數分別表示:畫布寬高、背景顏色、背景圖形狀、字體、屏蔽詞、最大詞的字體大小
wc = WordCloud(width=1024, height=768, background_color='white',  font_path='STKAITI.TTF',max_font_size=400, random_state=50)
# 將分詞後數據傳入雲圖
wc.generate_from_text(words)
wc.to_file('好友省份詞雲.jpg')

我們再通過可視化畫出一個Bar圖來更加清楚下,雖然結果很好,就是不知道最後那個省份是個什麼鬼,都哪裏來的,。。。。:
在這裏插入圖片描述
代碼如下:

# utf-8
import jieba
# 導入Counter類,用於統計值出現的次數
from collections import Counter
from pyecharts import Bar

Provinces = []
with open('friends.txt', mode='r', encoding='utf-8') as f:
    rows = f.readlines()
    for row in rows:
        Province = row.split(',')[3]
        if Province != '':
            Provinces.append(Province)
words = []
for cutword in jieba.cut(str(Provinces), cut_all=False):
    if cutword not in ['_', '-', ',', '(', ')', '(', ')', ' ', "'"]:# 排除下劃線、短橫線、逗號、空格、單引號 防止出錯
        words.append(cutword)
data_top10 = Counter(words).most_common(10)  # 返回出現次數最多的前10條
# print(data_top10)
bar = Bar('好友省份數量統計TOP10', '', title_pos='center', width=1200, height=600)
attr, value = bar.cast(data_top10)
bar.add('', attr, value, visual_range=[0, 200], is_visualmap=True, is_label_show=True)
bar.render('好友省份數量統計TOP10.html')

3.4分析朋友圈的個性簽名

寫到這裏,我看了下數據,發現有很多人忘了寫呀,這可是我需要的東西,你不寫多不好。嗯我在也就這裏說說。嘿嘿。不過說回來,通過詞雲分析我大概也分析出個東東來。
看來部分朋友,class沒學好好啊,都擱這寫呢!哈哈
在這裏插入圖片描述
代碼實現:

#utf-8

import jieba
from wordcloud import WordCloud

# 獲取全部的個性簽名
Signatures = []
with open('friends.txt', 'r', encoding='utf-8') as f:
    rows = f.readlines()
    for row in rows:
        Signature = row.split(',')[5]
        if Signature != '':
            # print(City)
            Signatures.append(Signature)
# 設置分詞 False精準模式分詞、True全模式分詞
split = jieba.cut(str(Signatures), cut_all=False)
words = ' '.join(split)  # 以空格進行拼接
# print(words)
# WordCloud()函數的詞雲參數分別表示:畫布寬高、背景顏色、背景圖形狀、字體、屏蔽詞、最大詞的字體大小
wc = WordCloud(width=1024, height=768, background_color='white',  font_path='STKAITI.TTF',max_font_size=400, random_state=50)
# 將分詞後數據傳入雲圖
wc.generate_from_text(words)
wc.to_file('好友個性簽名詞雲.jpg')

最後了,重磅來襲,輸出所有朋友圈的頭像合成在一張圖片上

先看下效果圖,當然了,我打馬賽克了,不然認識的人看見,發現是我寫的,那我就準備new一個自己來了。開玩笑,哈哈。
在這裏插入圖片描述
具體實現完整代碼如下:

import itchat
import os
import math
from PIL import Image

# 獲取數據
def download_image():
    # 掃描二維碼登陸微信,即通過網頁版微信登陸
    itchat.auto_login()
    # 返回一個包含用戶信息字典的列表
    friends = itchat.get_friends(update=True)
    #  在當前位置創建一個用於存儲頭像的目錄wechatImages
    base_path = 'wechatImages'
    if not os.path.exists(base_path):
        os.mkdir(base_path)

    # 獲取所有好友頭像
    for friend in friends:
        # 獲取頭像數據
        img_data = itchat.get_head_img(userName = friend['UserName'])
        #判斷備註名是否爲空
        if friend['RemarkName'] != '':
            img_name = friend['RemarkName']
        else :
            img_name = friend['NickName']
         #   在實際操作中如果文件名中含有*標誌,會報錯。則直接可以將其替換掉
        if img_name is "*":
            img_name = ""
        #通過os.path.join()函數來拼接文件名
        img_file = os.path.join(base_path, img_name + '.jpg')
        print(img_file)
        with open(img_file, 'wb') as file:
            file.write(img_data)


# 拼接頭像
def join_image():
    base_path = 'wechatImages'
    files = os.listdir(base_path) #返回指定的文件或文件夾的名字列表
    print(len(files))
    each_size = int(math.sqrt(float(6400 * 6400) / len(files)))#計算每個粘貼圖片的邊長
    lines = int(6400 / each_size)#計算總共有多少行
    print(lines)
    image = Image.new('RGB', (6400, 6400))# new(mode, size, color=0) 定義一張大小爲640*640大小的圖片,不給出第三個參數默認爲黑色
    x = 0 #定義橫座標
    y = 0 #定義縱座標
    for file_name in files:
        img = Image.open(os.path.join(base_path, file_name)) #找到/打開圖片
        img = img.resize((each_size, each_size), Image.ANTIALIAS)#實現圖片同比例縮放,Image.ANTIALIAS添加濾鏡效果
        image.paste(img, (x * each_size, y * each_size))#將縮放後的照片放到對應的座標下
        x += 1
        if x == lines:#如果每行的粘貼內容夠了,則換行
            x = 0
            y += 1
    image.save('jointPic.jpg')#最後將全部的照片保存下來

if __name__ == '__main__':
    # download_image()
    join_image()



寫到這本片就完了,我的頭髮還是那麼茂密!
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章