1. 程式人生 > >python實戰專案示例 :揭祕微信朋友圈

python實戰專案示例 :揭祕微信朋友圈

通過python,連線到微信賬號,收集好友性別、城市、個性簽名等公開資訊,使用 Python 進行資料統計與分析,得到你專屬的朋友圈的分析報告!

1、準備工作

1.1 環境配置

編譯環境:Windows10

程式語言:Python3.6

編譯器IDE:Pycharm

瀏覽器工具:Chrome瀏覽器

1.2 wxpy庫介紹

採用第三方庫wxpy進行微信登入和資訊獲取。

具體細節文件參考https://wxpy.readthedocs.io/zh/latest/

wxpy的一些常見的場景

  • 控制路由器、智慧家居等具有開放介面的玩意兒
  • 執行指令碼時自動把日誌傳送到你的微信
  • 加群主為好友,自動拉進群中
  • 跨號或跨群轉發訊息
  • 自動陪人聊天
  • 逗人玩
  • ...

總而言之,可用來實現各種微信個人號的自動化操作

1.3 wxpy庫安裝

wxpy 支援 Python 3.4-3.6,以及 2.7 版本

將下方命令中的 “pip” 替換為 “pip3” 或 “pip2”,可確保安裝到對應的 Python 版本中

  1. 從 PYPI 官方源下載安裝 (在國內可能比較慢或不穩定):
pip install -U wxpy
  1. 從豆瓣 PYPI 映象源下載安裝 (推薦國內使用者選用):
pip install -U wxpy -i "https://pypi.doubanio.com/simple/"

1.4 登入微信

使用bot()登入微信

# 匯入模組
from wxpy import *
# 初始化機器人,掃碼登陸
bot = Bot()
# 獲取所有好友
my_friends = bot.friends()
print(type(my_friends))

輸出結果

Getting uuid of QR code.
Downloading QR code.
Please scan the QR code to log in.

彈出二維碼進行掃描,掃描後輸出

Please press confirm on your phone.
Loading the contact, this may take a little while.
Login successfully as XXXX
<class 'wxpy.api.chats.chats.Chats'>

2、微信好友性別統計

2.1 資料統計

統計性別

# 使用一個字典統計好友男性和女性的數量
sex_dict = {'male': 0, 'female': 0}

for friend in my_friends:
    # 統計性別
    if friend.sex == 1:
        sex_dict['male'] += 1
    elif friend.sex == 2:
        sex_dict['female'] += 1

print(sex_dict)

輸出結果

{'male': 194, 'female': 166}

2.2 資料展示

採用 ECharts餅圖 進行資料展示,左邊為JSON展示程式碼,右邊為資料圖

 修改JSON程式碼如下

option = {
    title : {
        text: '微信好友性別比例',
        subtext: '真實資料',
        x:'center'
    },
    tooltip : {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
    },
    legend: {
        orient : 'vertical',
        x : 'left',
        data:['男性','女性']
    },
    toolbox: {
        show : true,
        feature : {
            mark : {show: true},
            dataView : {show: true, readOnly: false},
            magicType : {
                show: true, 
                type: ['pie', 'funnel'],
                option: {
                    funnel: {
                        x: '25%',
                        width: '50%',
                        funnelAlign: 'left',
                        max: 1548
                    }
                }
            },
            restore : {show: true},
            saveAsImage : {show: true}
        }
    },
    calculable : true,
    series : [
        {
            name:'訪問來源',
            type:'pie',
            radius : '55%',
            center: ['50%', '60%'],
            data:[
                {value:194, name:'男性'},
                {value:166, name:'女性'}
            ]
        }
    ]
};        

點選“重新整理” ,顯示如下

3、微信好友城市統計

3.1 資料統計

統計城市,此處只統計全國範圍內的城市,如果寫了國外,則記為“其他”。

# 使用一個字典統計各省好友數量
province_dict = {'北京': 0, '上海': 0, '天津': 0, '重慶': 0,
    '河北': 0, '山西': 0, '吉林': 0, '遼寧': 0, '黑龍江': 0,
    '陝西': 0, '甘肅': 0, '青海': 0, '山東': 0, '福建': 0,
    '浙江': 0, '臺灣': 0, '河南': 0, '湖北': 0, '湖南': 0,
    '江西': 0, '江蘇': 0, '安徽': 0, '廣東': 0, '海南': 0,
    '四川': 0, '貴州': 0, '雲南': 0,
    '內蒙古': 0, '新疆': 0, '寧夏': 0, '廣西': 0, '西藏': 0,
    '香港': 0, '澳門': 0, '其他': 0 }

# 統計省份
for friend in my_friends:
    if friend.province in province_dict.keys():
        province_dict[friend.province] += 1
    if friend.province not in province_dict.keys():
        province_dict['其他'] += 1
    

# 為了方便資料的呈現,生成JSON Array格式資料
data = []
for key, value in province_dict.items():
    data.append({'name': key, 'value': value})

print(data)

輸出結果

[{'name': '北京', 'value': 11}, {'name': '上海', 'value': 19}, {'name': '天津', 'value': 1}, {'name': '重慶', 'value': 5}, {'name': '河北', 'value': 4}, {'name': '山西', 'value': 1}, {'name': '吉林', 'value': 4}, {'name': '遼寧', 'value': 3}, {'name': '黑龍江', 'value': 4}, {'name': '陝西', 'value': 5}, {'name': '甘肅', 'value': 1}, {'name': '青海', 'value': 0}, {'name': '山東', 'value': 9}, {'name': '福建', 'value': 6}, {'name': '浙江', 'value': 128}, {'name': '臺灣', 'value': 1}, {'name': '河南', 'value': 6}, {'name': '湖北', 'value': 7}, {'name': '湖南', 'value': 3}, {'name': '江西', 'value': 5}, {'name': '江蘇', 'value': 15}, {'name': '安徽', 'value': 40}, {'name': '廣東', 'value': 10}, {'name': '海南', 'value': 1}, {'name': '四川', 'value': 2}, {'name': '貴州', 'value': 0}, {'name': '雲南', 'value': 0}, {'name': '內蒙古', 'value': 0}, {'name': '新疆', 'value': 0}, {'name': '寧夏', 'value': 0}, {'name': '廣西', 'value': 1}, {'name': '西藏', 'value': 0}, {'name': '香港', 'value': 0}, {'name': '澳門', 'value': 0}, {'name': '其他', 'value': 112}]

3.2 資料展示

本想採用ECharts地圖 來進行好友分佈的資料呈現,結果網站在維護,無法開啟,故通過下載echarts相關元件和js檔案進行展示。

echarts官網下載  http://echarts.baidu.com/download.html

echarts原始碼壓縮包、jquery.js、echarts.min.js、china.js下載
連結:https://pan.baidu.com/s/1EIN4j0Avjut46Ljku1_SMQ 密碼:9dtm
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=EDGE">
    <title>ECharts</title>
    <!--<link rel="stylesheet" type="text/css" href="css/main.css"/>-->
    <script src="jquery.js"></script>
    <script src="echarts.min.js"></script>
    <script src="china.js"></script>
    <style>#china-map {width:1000px; height: 1000px;margin: auto;}</style>
</head>
<body>
<div id="china-map"></div>
<script>
    var myChart = echarts.init(document.getElementById('china-map'));
    var option = {
        title : {
            text: '微信好友全國分佈圖',
            subtext: '真實資料',
            x:'center'
        },
        tooltip : {//提示框元件。
            trigger: 'item'//資料項圖形觸發,主要在散點圖,餅圖等無類目軸的圖表中使用。
        },
        legend: {
            orient: 'horizontal',//圖例的排列方向
            x:'left',//圖例的位置
            data:['好友數量']
        },
        dataRange: {
            min: 0,
            max: 150,
            x: 'left',
            y: 'bottom',
            text:['高','低'],           // 文字,預設為數值文字
            calculable : true
        },
        //左側小導航圖示
        visualMap: {//顏色的設定  dataRange
            show : true,
            x: 'left',
            y: 'center',
            splitList: [
                {start: 0, end: 5},
                {start: 6, end: 10},
                {start: 11, end: 15},
                {start: 16, end: 20},
                {start: 21, end: 40, label: '21 到 40(自定義label)'},
                {start: 41, label: '5(自定義特殊顏色)', color: 'black'},
            ],
//            min: 0,
//            max: 2500,
//            calculable : true,//顏色呈條狀
            text:['高','低'],// 文字,預設為數值文字
            <!--color: ['#E0022B', '#E09107', '#A3E00B']-->
            color: ['#5475f5', '#9feaa5', '#85daef','#74e2ca', '#e6ac53', '#9fb5ea']
        },
        toolbox: {//工具欄
            show: true,
            orient : 'vertical',//工具欄 icon 的佈局朝向
            x: 'right',
            y: 'center',
            feature : {//各工具配置項。
                mark : {show: true},
                dataView : {show: true, readOnly: false},//資料檢視工具,可以展現當前圖表所用的資料,編輯後可以動態更新。
                restore : {show: true},//配置項還原。
                saveAsImage : {show: true}//儲存為圖片。
            }
        },
        roamController: {//控制地圖的上下左右放大縮小 圖上沒有顯示
            show: true,
            x: 'right',
            mapTypeControl: {
                'china': true
            }
        },
        //配置屬性
        series : [
            {
                name: '好友數量',
                type: 'map',
                mapType: 'china',
                roam: false,//是否開啟滑鼠縮放和平移漫遊
                //地圖區域的多邊形 圖形樣式;
                itemStyle:{
                    normal:{label:{show:true}},//是圖形在預設狀態下的樣式;//是否顯示標籤
		            emphasis:{label:{show:true}}//是圖形在高亮狀態下的樣式,比如在滑鼠懸浮或者圖例聯動高亮時
                },
                top:"3%",//元件距離容器的距離
                data:[
                    {'name': '北京', 'value': 11},
                    {'name': '上海', 'value': 19},
                    {'name': '天津', 'value': 1},
                    {'name': '重慶', 'value': 5},
                    {'name': '河北', 'value': 4},
                    {'name': '山西', 'value': 1},
                    {'name': '吉林', 'value': 4},
                    {'name': '遼寧', 'value': 3},
                    {'name': '黑龍江', 'value': 4},
                    {'name': '陝西', 'value': 5},
                    {'name': '甘肅', 'value': 1},
                    {'name': '青海', 'value': 0},
                    {'name': '山東', 'value': 9},
                    {'name': '福建', 'value': 6},
                    {'name': '浙江', 'value': 128},
                    {'name': '臺灣', 'value': 1},
                    {'name': '河南', 'value': 6},
                    {'name': '湖北', 'value': 7},
                    {'name': '湖南', 'value': 3},
                    {'name': '江西', 'value': 5},
                    {'name': '江蘇', 'value': 15},
                    {'name': '安徽', 'value': 40},
                    {'name': '廣東', 'value': 10},
                    {'name': '海南', 'value': 1},
                    {'name': '四川', 'value': 2},
                    {'name': '貴州', 'value': 0},
                    {'name': '雲南', 'value': 0},
                    {'name': '內蒙古', 'value': 0},
                    {'name': '新疆', 'value': 0},
                    {'name': '寧夏', 'value': 0},
                    {'name': '廣西', 'value': 1},
                    {'name': '西藏', 'value': 0},
                    {'name': '香港', 'value': 0},
                    {'name': '澳門', 'value': 0},
                ]
            }
        ]
    };
    myChart.setOption(option);
    myChart.on('mouseover', function (params) {
        var dataIndex = params.dataIndex;
        console.log(params);
    });
</script>
</body>
</html>

執行程式碼後,顯示結果

4、微信好友個性簽名統計

4.1 資料統計

統計個性簽名,並存至本地'signatures.txt'

import re

def write_txt_file(path, txt):
    '''
    寫入txt文字
    '''
    with open(path, 'a', encoding='gb18030', newline='') as f:
        f.write(txt)

# 統計簽名
for friend in my_friends:
    # 對資料進行清洗,將標點符號等對詞頻統計造成影響的因素剔除
    pattern = re.compile(r'[一-龥]+')
    filterdata = re.findall(pattern, friend.signature)
    write_txt_file('signatures.txt', ' '.join(filterdata))

4.2 資料展示

4.2.1 安裝庫

對個性簽名文件做文字處理,需要安裝以下第三方庫檔案

pip install jieba
pip install pandas
pip install numpy
pip install scipy
pip install wordcloud

4.2.2 讀取文字

def read_txt_file(path):
    '''
    讀取txt文字
    '''
    with open(path, 'r', encoding='gb18030', newline='') as f:
        return f.read()

4.2.3 載入停用詞

百度“停用詞表”,網上資源有很多可以下載,此處由於個性簽名的文字較小,故只剔除了部分常見停用詞,如的、了、啦、於、都、一、而、就、之等。

content = read_txt_file(txt_filename)
segment = jieba.lcut(content)
words_df=pd.DataFrame({'segment':segment})

stopwords=pd.read_csv("stopwords.txt",index_col=False,quoting=3,sep=" ",names=['stopword'],encoding='utf-8')
words_df=words_df[~words_df.segment.isin(stopwords.stopword)]

4.2.4 詞頻統計

import numpy

words_stat = words_df.groupby(by=['segment'])['segment'].agg({"計數":numpy.size})
    words_stat = words_stat.reset_index().sort_values(by=["計數"],ascending=False)

4.2.5 詞雲展示

from scipy.misc import imread
from wordcloud import WordCloud, ImageColorGenerator


# 設定詞雲屬性
color_mask = imread('python.jpg')
wordcloud = WordCloud(font_path="simhei.ttf",   # 設定字型可以顯示中文
                background_color="white",       # 背景顏色
                max_words=100,                  # 詞雲顯示的最大詞數
                mask=color_mask,                # 設定背景圖片
                max_font_size=150,              # 字型最大值
                random_state=42,
                width=1000, height=860, margin=2,# 設定圖片預設的大小,但是如果使用背景圖片的話,                                                   # 那麼儲存的圖片大小將會按照其大小儲存,margin為詞語邊緣距離
                )

# 生成詞雲, 可以用generate輸入全部文字,也可以我們計算好詞頻後使用generate_from_frequencies函式
word_frequence = {x[0]:x[1]for x in words_stat.head(100).values}
print(word_frequence)
word_frequence_dict = {}
for key in word_frequence:
    word_frequence_dict[key] = word_frequence[key]

wordcloud.generate_from_frequencies(word_frequence_dict)
# 從背景圖片生成顏色值  
image_colors = ImageColorGenerator(color_mask) 
# 重新上色
wordcloud.recolor(color_func=image_colors)
# 儲存圖片
wordcloud.to_file('output.jpg')
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

下圖左為背景圖'background.jpg',右為詞雲圖'output.png'

 

      

5、總結與展望

通過wxpy獲取微信好友的性別、地區、個性簽名等資訊分析朋友圈好友基本屬性,也可通過wxpy的其他功能進行微信分析,具體拓展可以根據興趣繼續實現https://wxpy.readthedocs.io/zh/latest/

6、完整程式碼

#-*- coding: utf-8 -*-
import re
import jieba
import numpy
import pandas as pd
import matplotlib.pyplot as plt
from scipy.misc import imread
from wordcloud import WordCloud, ImageColorGenerator
from wxpy import *


def write_txt_file(path, txt):
    '''
    寫入txt文字
    '''
    with open(path, 'a', encoding='gb18030', newline='') as f:
        f.write(txt)

def read_txt_file(path):
    '''
    讀取txt文字
    '''
    with open(path, 'r', encoding='gb18030', newline='') as f:
        return f.read()

def login():
    # 初始化機器人,掃碼登陸
    bot = Bot()

    # 獲取所有好友
    my_friends = bot.friends()

    print(type(my_friends))
    return my_friends

def show_sex_ratio(friends):
    # 使用一個字典統計好友男性和女性的數量
    sex_dict = {'male': 0, 'female': 0}

    for friend in friends:
        # 統計性別
        if friend.sex == 1:
            sex_dict['male'] += 1
        elif friend.sex == 2:
            sex_dict['female'] += 1

    print(sex_dict)

def show_area_distribution(friends):
    # 使用一個字典統計各省好友數量
    province_dict = {'北京': 0, '上海': 0, '天津': 0, '重慶': 0,
        '河北': 0, '山西': 0, '吉林': 0, '遼寧': 0, '黑龍江': 0,
        '陝西': 0, '甘肅': 0, '青海': 0, '山東': 0, '福建': 0,
        '浙江': 0, '臺灣': 0, '河南': 0, '湖北': 0, '湖南': 0,
        '江西': 0, '江蘇': 0, '安徽': 0, '廣東': 0, '海南': 0,
        '四川': 0, '貴州': 0, '雲南': 0,
        '內蒙古': 0, '新疆': 0, '寧夏': 0, '廣西': 0, '西藏': 0,
        '香港': 0, '澳門': 0, '其他': 0 }

    # 統計省份
    for friend in friends:
        if friend.province in province_dict.keys():
            province_dict[friend.province] += 1
        if friend.province not in province_dict.keys():
            province_dict['其他'] += 1

    # 為了方便資料的呈現,生成JSON Array格式資料
    data = []
    for key, value in province_dict.items():
        data.append({'name': key, 'value': value})

    print(data)

def show_signature(friends):
    # 統計簽名
    for friend in friends:
        # 對資料進行清洗,將標點符號等對詞頻統計造成影響的因素剔除
        pattern = re.compile(r'[一-龥]+')
        filterdata = re.findall(pattern, friend.signature)
        write_txt_file('signatures.txt', '\n'.join(filterdata))

    # 讀取檔案
    content = read_txt_file('signatures.txt')
    segment = jieba.lcut(content)
    words_df = pd.DataFrame({'segment':segment})

    # 讀取stopwords
    stopwords = pd.read_csv("stopwords.txt",index_col=False,quoting=3,sep=" ",names=['stopword'],encoding='utf-8')
    words_df = words_df[~words_df.segment.isin(stopwords.stopword)]
    print(words_df)

    words_stat = words_df.groupby(by=['segment'])['segment'].agg({"計數":numpy.size})
    words_stat = words_stat.reset_index().sort_values(by=["計數"],ascending=False)

    # 設定詞雲屬性
    color_mask = imread('python.jpg')
    wordcloud = WordCloud(font_path="simhei.ttf",   # 設定字型可以顯示中文
                    background_color="white",       # 背景顏色
                    max_words=100,                  # 詞雲顯示的最大詞數
                    mask=color_mask,                # 設定背景圖片
                    max_font_size=150,              # 字型最大值
                    random_state=42,
                    width=1000, height=860, margin=2,# 設定圖片預設的大小,但是如果使用背景圖片的話,
                                                     # 那麼儲存的圖片大小將會按照其大小儲存,margin為詞語邊緣距離
                    )

    # 生成詞雲, 可以用generate輸入全部文字,也可以我們計算好詞頻後使用generate_from_frequencies函式
    word_frequence = {x[0]:x[1]for x in words_stat.head(100).values}
    print(word_frequence)
    word_frequence_dict = {}
    for key in word_frequence:
        word_frequence_dict[key] = word_frequence[key]

    wordcloud.generate_from_frequencies(word_frequence_dict)
    # 從背景圖片生成顏色值
    image_colors = ImageColorGenerator(color_mask)
    # 重新上色
    wordcloud.recolor(color_func=image_colors)
    # 儲存圖片
    wordcloud.to_file('output.jpg')
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()

def main():
    friends = login()
    show_sex_ratio(friends)
    show_area_distribution(friends)
    show_signature(friends)

if __name__ == '__main__':
    main()