1. 程式人生 > >【程式碼】用Python玩轉微信,echarts餅圖,WordCloud雲圖,自動回覆訊息,好友地區熱圖

【程式碼】用Python玩轉微信,echarts餅圖,WordCloud雲圖,自動回覆訊息,好友地區熱圖

參考用Python玩轉微信(一),做了一些修改

import re
import os
import time
import itchat
from echarts import Echart, Legend, Pie
import wordcloud
from wordcloud import WordCloud, ImageColorGenerator
import jieba
import numpy as np
import PIL.Image as Img
import matplotlib.pyplot as plt


# 登入,傳送訊息到filehelper
# itchat.login()
# itchat.send(u'hello', 'filehelper')

# 登入狀態儲存,但似乎還是彈出二維碼
itchat.auto_login(hotReload=True)
itchat.dump_login_status()

# 微信好友男女比例
friends = itchat.get_friends(update=True)[0:]
# 男,女,其他,總人數,friends[0]是自己
male = female = other = 0
for i in friends[1:]:
    sex = i['Sex']
    if sex == 1:
        male += 1
    elif sex == 2:
        female += 1
    else:
        other += 1
total = len(friends[1:])

# 百分比圓餅圖
chart = Echart(u'{}微信好友性別比例'.format(friends[0]['NickName']), 'from WeChat')
chart.use(Pie('WeChat',
              [
                  {'value': male, 'name': u'男性 %.2f%%' % (float(male)/total*100)},
                  {'value': female, 'name': u'女性 %.2f%%' % (float(female) / total * 100)},
                  {'value': other, 'name': u'不明 %.2f%%' % (float(other) / total * 100)},

              ],
            radius = ['50%', '70%']
            ))
chart.use(Legend(['male', 'female', 'other']))
del chart.json['xAxis']
del chart.json['yAxis']
chart.plot()
# 登入
itchat.login()
# 好友個性簽名
signature_ls = []
friends = itchat.get_friends(update=True)[:]
for friend in friends:
    signature = friend['Signature'].strip()
    signature = re.sub('<span.*?</span>', '', signature)
    signature_ls.append(signature)
# 長簽名字串
raw_signatures = ''.join(signature_ls)
# print(raw_signatures)

# jieba分詞,注意分詞後要用' '連線起來
text = jieba.cut(raw_signatures, cut_all=True)
text = ' '.join(text)
text = text.replace('\n', '')
# print(text)


# 預設顏色和樣式
my_wordcloud = WordCloud(background_color='white',
                         max_words=2000,
                         max_font_size=40,
                         random_state=42,
                         font_path=r'C:\Windows\Fonts\ARIALUNI.TTF'
                         ).generate(text)

plt.imshow(my_wordcloud)
plt.axis('off')
plt.show()

# 選擇圖片模板做顏色和樣式
dr = os.path.dirname(__file__)
coloring = np.array(Img.open(os.path.join(dr, 'hdImg.jpg')))
my_wordcloud = WordCloud(background_color='white',
                         max_words=2000,
                         mask=coloring,
                         max_font_size=50,
                         random_state=42,
                         font_path=r'C:\Windows\Fonts\ARIALUNI.TTF'
                         ).generate(text)

image_colors = ImageColorGenerator(coloring)
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis('off')
plt.show()

# 儲存到檔案,傳送到filehelper
my_wordcloud.to_file('wechat_cloud.png')
itchat.send_image('wechat_cloud.png', 'filehelper')

在這裡插入圖片描述

# 裝飾器自動回覆文字訊息
@itchat.msg_register('Text')
def reply(msg):
    if not msg['FromUserName'] == myUserName:
        # 將訊息備份到filehelper
        itchat.send_msg(u'{}收到{}的訊息{}'.format(
                                                    time.strftime('%Y-%m-%d %H:%M:%S'),
                                                    msg['User']['NickName'],
                                                    msg['Text']), 'filehelper')
	# 如果是好友appium發來的訊息,回覆‘thankyou’
        if msg['User']['NickName'] == 'appium':
            return 'thankyou'


if __name__ == '__main__':
    itchat.auto_login()
    myUserName = itchat.get_friends(update=True)[0]['UserName']
    # 自動回覆訊息
    itchat.run()

Geopy模組幾乎用不了,使用百度AK獲取指定地區的經緯度,但是百度熱圖例項打不開,最終用高德地圖熱圖例項實現。。。
注意json還是要用json庫的dumps實現,自己瞎編輯的json格式無法識別,估計無法正確讀入.js檔案的json資料吧。。。。

# coding=gbk
import itchat
import requests
import json

# 獲取微信好友城市列表,去掉未設定城市的好友的空串''
itchat.auto_login()
friends = itchat.get_friends(update=True)[:]

citys = []
for friend in friends:
    if friend['City'] != '':
        citys.append(friend['City'])


# 申請百度的AK,取得微信好友的經緯度
def geocode(address):
    url = 'http://api.map.baidu.com/geocoder/v2/?address=' \
          + address + '&output=json&ak=7LpPYrfuXuGdDmRELo2TSsLenCKtvdMi'
    response = requests.get(url)
    data = response.json()
    # 返回經緯度字典
    return data['result']['location']


# 將經緯度,新增"value"=1,作為熱點儲存到列表中
points = []
for city in citys:
    location = geocode(city)
    location['value'] = 1
    points.append(location)

# 將字典的列表轉成json格式,賦值到wechat_heatmap.html的heatmapData.js檔案中: var heatmapData = ...
points_json = json.dumps(points)
print(points_json)

# 最後在wechat_heatmap.html複製高德熱力圖例項原始碼 https://lbs.amap.com/api/loca-api/demos/loca_heatmap/loca_heatmap_3d/
# wechat_heatmap.html中新增高德地圖申請的web端Key
# <script src="//webapi.amap.com/loca?v=1.2.0&key=8e801b290ca8dae42e46e36c72f2bfa3"></script>
# <script src="heatmapData.js"></script>
# .js和.html檔案在同級,開啟html檔案即可檢視熱力圖

在這裡插入圖片描述