用Python玩轉微信(一)

歡迎你們訪問個人我的網站《劉江的博客和教程》:www.liujiangblog.com

主要分享Python 及Django教程以及相關的博客

今天偶然看見http://www.cnblogs.com/jiaoyu121/p/6944398.html#top博客,用Python玩轉微信,寫得很是好。html

然而,貌似用的Python2版本,而且每次執行都要重複掃碼登陸,這對於我這種Python3的用戶是不行的。python

動起手來,本身幹!django

1. 安裝相應的庫

pip install itchat
pip install echarts-pythonjson

2. 實現登錄狀態保存:

import itchat

itchat.auto_login(hotReload=True)
itchat.dump_login_status()

這樣你就能夠保持一段時間登陸狀態,而不用每次運行代碼都要掃碼登陸了!windows

首次登陸,程序會彈出一個二維碼圖片窗口,用微信手機客戶端掃碼就能夠登陸了!
瀏覽器

3. 使用餅圖展現我的好友性別分佈

有一個echarts-python庫能夠幫助你方便的使用python代碼在瀏覽器中展現百度Echart圖。可是,可是,這個庫是Python2的,
Python3用起來水土不服,沒辦法只好根據錯誤修改庫的源碼!下圖顯示了應該改的兩個地方(其實還有不少地方)。
微信

改完庫的源碼,就能夠執行代碼了。借用前人的代碼,修改了一下:併發

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import itchat

itchat.auto_login(hotReload=True)
itchat.dump_login_status()

friends = itchat.get_friends(update=True)[:]
total = len(friends) - 1
male = female = other = 0

for friend in friends[1:]:
    sex = friend["Sex"]
    if sex == 1:
        male += 1
    elif sex == 2:
        female += 1
    else:
        other += 1
# print("男性好友:%.2f%%" % (float(male) / total * 100))
# print("女性好友:%.2f%%" % (float(female) / total * 100))
# print("其餘:%.2f%%" % (float(other) / total * 100))

from echarts import Echart, Legend, Pie
chart = Echart('%s的微信好友性別比例' % (friends[0]['NickName']), 'from WeChat')
chart.use(Pie('WeChat',
              [{'value': male, 'name': '男性 %.2f%%' % (float(male) / total * 100)},
               {'value': female, 'name': '女性 %.2f%%' % (float(female) / total * 100)},
               {'value': other, 'name': '其餘 %.2f%%' % (float(other) / total * 100)}],
              radius=["50%", "70%"]))
chart.use(Legend(["male", "female", "other"]))
del chart.json["xAxis"]
del chart.json["yAxis"]
chart.plot()

運行代碼,測試一下,成功在瀏覽器展現出來了:app

我好想暴露了什麼....echarts

4. 好友個性簽名詞雲

分析好友信息,能發現個性簽名,能夠用它作詞雲。

for friend in friends:
        signature = friend["Signature"].strip()
        signature = re.sub("<span.*>", "", signature)
        signature_list.append(signature)
    raw_signature_string = ''.join(signature_list)

上面利用正則,去掉一些相似<span class=....>以及空格之類的無用字符。而後把他們連成一個大的長的字符串

pip install jieba
這個庫是用來將字符串拆分紅不重複的一個一個的詞的,貌似都是2字詞。
pip install wordcloud
安裝詞雲庫,會彈出錯誤以下圖

怎麼辦?去http://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud 頁面下載所需的wordcloud模塊的whl文件

下載後進執行「pip install wordcloud-1.3.1-cp36-cp36m-win_amd64.whl」,就能夠了。意文件路徑。

利用jieba的cut方法將字符串裁成一個一個的詞,而後用空格,將它們又連起來。注意是用空格哦!千萬別看錯了!

text = jieba.cut(raw_signature_string, cut_all=True)
    target_signatur_string = ' '.join(text)

再導入一些輔助的庫

import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import PIL.Image as Image
import os
import numpy as np

這些庫,有的會自動安裝,有的可能要你本身裝,好比pip install numpy

而後提供一張圖片。

wordcloud會根據這張圖片在x和y軸上的顏色以及範圍等等,佈置詞雲。這個過程是經過numpy的矩陣和matplot的畫圖能力實現的。

下面的源碼是根據原文的代碼略微修改後的。

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import itchat
import re
import jieba


def echart_pie(friends):
    total = len(friends) - 1
    male = female = other = 0

    for friend in friends[1:]:
        sex = friend["Sex"]
        if sex == 1:
            male += 1
        elif sex == 2:
            female += 1
        else:
            other += 1
    from echarts import Echart, Legend, Pie
    chart = Echart('%s的微信好友性別比例' % (friends[0]['Name']), 'from WeChat')
    chart.use(Pie('WeChat',
                  [{'value': male, 'name': '男性 %.2f%%' % (float(male) / total * 100)},
                   {'value': female, 'name': '女性 %.2f%%' % (float(female) / total * 100)},
                   {'value': other, 'name': '其餘 %.2f%%' % (float(other) / total * 100)}],
                  radius=["50%", "70%"]))
    chart.use(Legend(["male", "female", "other"]))
    del chart.json["xAxis"]
    del chart.json["yAxis"]
    chart.plot()


def word_cloud(friends):
    import matplotlib.pyplot as plt
    from wordcloud import WordCloud, ImageColorGenerator
    import PIL.Image as Image
    import os
    import numpy as np
    d = os.path.dirname(__file__)
    my_coloring = np.array(Image.open(os.path.join(d, "2.png")))
    signature_list = []
    for friend in friends:
        signature = friend["Signature"].strip()
        signature = re.sub("<span.*>", "", signature)
        signature_list.append(signature)
    raw_signature_string = ''.join(signature_list)
    text = jieba.cut(raw_signature_string, cut_all=True)
    target_signatur_string = ' '.join(text)

    my_wordcloud = WordCloud(background_color="white", max_words=2000, mask=my_coloring,
                             max_font_size=40, random_state=42,
                             font_path=r"C:\Windows\Fonts\simhei.ttf").generate(target_signatur_string)
    image_colors = ImageColorGenerator(my_coloring)
    plt.imshow(my_wordcloud.recolor(color_func=image_colors))
    plt.imshow(my_wordcloud)
    plt.axis("off")
    plt.show()
    # 保存圖片 併發送到手機
    my_wordcloud.to_file(os.path.join(d, "wechat_cloud.png"))
    itchat.send_image("wechat_cloud.png", 'filehelper')


itchat.auto_login(hotReload=True)
itchat.dump_login_status()

friends = itchat.get_friends(update=True)[:]

# echart_pie(friends)

word_cloud(friends)

運行後的效果是這樣的:

windows下的顯示效果然不怎麼樣!

相關文章
相關標籤/搜索