2019 第 41 篇,總第 65 篇文章python
本文大約 4000 字,閱讀大約須要 12 分鐘android
最近簡單運用 itchat 這個庫來實現一些簡單的應用,主要包括如下幾個應用:nginx
統計保存好友的數量和信息git
統計和保存關注的公衆號數量和信息程序員
簡單生成好友頭像的圖片牆,利用一個第三方庫生成馬賽克風格的圖片牆github
itchat 的 github 項目地址以下,這是一個開源的微信我的接口:算法
https://github.com/littlecodersh/ItChat微信
這個庫的安裝也很簡單,直接用 pip install itchat
便可安裝cookie
接下來就開始介紹如何利用這個庫來實現上述操做。session
1. 統計保存好友的數量和信息
首先是微信登陸,簡單的幾行代碼便可實現:
import itchat
# 避免頻繁掃描二維碼登陸
itchat.auto_login(hotReload=True)
itchat.dump_login_status()
運行這段代碼後,就會彈出一個二維碼,進行掃描登陸,其中 hotReload=True
是保證不用每次運行程序都須要彈出二維碼掃描登陸。
而後是獲取好友的信息:
we_friend = itchat.get_friends(update=True)[:]
這裏 we_friend
就是保存了好友信息的一個字典,而且 we_friend[0]
是保存用戶本身的信息,從we_friend[1]
開始纔是真正的好友的信息,這裏咱們將主要保存如下信息:
key | 含義 |
---|---|
NickName | 暱稱 |
RemarkName | 備註 |
Sex | 性別 |
Province | 省份 |
City | 城市 |
Signature | 簽名 |
保存好友的信息代碼以下:
friends = we_friend[1:]
total_numbers = len(friends)
print('你的好友數量爲: {}'.format(total_numbers))
friend_infos_dict = {}
for fri_info in friends:
for key in friend_key:
if friend_infos_dict.get(key, False):
friend_infos_dict[key].append(fri_info[key])
else:
friend_infos_dict[key] = [fri_info[key]]
# 保存信息
fri_save_file_name = os.path.join(save_file_path, '好友信息.csv')
df = pd.DataFrame(friend_infos_dict)
df.to_csv(fri_save_file_name, sep=',')
其中 save_file_path
是指定保存好友信息文件的文件夾路徑,
2. 保存公衆號信息
獲取公衆號信息並保存的代碼以下:
# 公衆號獲取的信息內容,分別是暱稱、城市、城市、簽名
mps_key = ['NickName', 'City', 'Province', 'Signature']
# 獲取公衆號信息
mps = itchat.get_mps(update=True)
mps_num = len(mps)
print('你關注的公衆號數量: {}'.format(mps_num))
mps_save_file_name = os.path.join(save_file_path, '公衆號信息.csv')
mps_dict = {}
for mp in mps:
for key in mps_key:
if mps_dict.get(key, False):
mps_dict[key].append(mp[key])
else:
mps_dict[key] = [mp[key]]
df = pd.DataFrame(mps_dict)
df.to_csv(mps_save_file_name, sep=',', encoding='utf-8')
3. 生成好友頭像圖片牆
首先一樣須要獲取好友的頭像,並保存到本地,代碼以下:
def save_head_photo(save_photo_dir):
itchat.auto_login(hotReload=True)
itchat.dump_login_status()
friends = itchat.get_friends(update=True)[1:]
# 採集好友頭像並保存到本地
num = 0
for fri in friends:
img = itchat.get_head_img(userName=fri['UserName'])
img_path = os.path.join(save_photo_dir, str(num) + '.jpg')
if not os.path.exists(img_path):
file_image = open(img_path, 'wb')
file_image.write(img)
file_image.close()
num += 1
print('完成好友頭像保存至路徑: ', save_photo_dir)
其中獲取頭像的函數是 itchat.get_head_image()
。
接着就是生成好友頭像的圖片牆,這裏有兩種方式,第一種是比較常規的生成方法。首先須要導入如下庫
import itchat
import math
import PIL.Image as Image
import os
接着是設置畫布大小及每行的頭像數量,頭像的大小,代碼是:
# 畫布大小
image_size = 1280
# 算出每張圖片的大小多少合適
each_size = int(math.sqrt(float(image_size * image_size) / len(ls)))
# 每行圖片數量
lines = int(image_size / each_size)
print('each_size={}, lines={}'.format(each_size, lines))
# 建立 1280*1280 的畫布
image = Image.new('RGBA', (image_size, image_size))
利用的是 pillow
庫,安裝方式是 pip install pillow
。這裏我設置的畫布大小就是 1280 * 1280。
而後就是讀取保存的頭像,並逐一粘貼到畫布上,代碼以下:
# 讀取保存的好友頭像圖片
ls = os.listdir(save_photo_dir)
for i in range(0, len(ls)):
try:
img_path = os.path.join(save_photo_dir, str(i) + ".jpg")
img = Image.open(img_path)
except IOError:
print("Error for image: {}".format(img_path))
else:
img = img.resize((each_size, each_size), Image.ANTIALIAS)
image.paste(img, (x * each_size, y * each_size)) # 粘貼位置
x += 1
if x == lines: # 換行
x = 0
y += 1
image.save(os.path.join(os.getcwd(), "好友頭像拼接圖.jpg"))
第二種是參考了 當 Python 趕上你的微信好友 介紹的第三方庫 photomosaic
,安裝方法也很簡單:
pip install photomosaic
這個第三方庫能夠生成蒙太奇馬賽克風格的圖片或者視頻。
實現代碼以下:
import photomosaic as pm
def create_photomosaic(save_photo_dir, background_photo):
# 讀取背景圖片
bg_photo = pm.imread(background_photo)
# 讀取好友頭像圖片,定義圖片庫
pool = pm.make_pool(os.path.join(save_photo_dir, '*.jpg'))
# 製做 50*50 的拼圖馬賽克
image = pm.basic_mosaic(bg_photo, pool, (50, 50))
# 保存結果
pm.imsave('馬賽克好友頭像圖片.jpg', image)
其中上述的四行代碼也是最基本的使用代碼,包括:
選擇背景圖片
定義圖片庫
製做馬賽克拼圖
保存圖片
這裏我簡單選擇了下面這張背景圖片:
生成結果以下:

小結
簡單運用 itchat 實現了以上三個小應用,實際上還能夠有更多的應用,好比再根據好友信息分析性別比例、好友區域分佈、簽名的情感分析、關注的公衆號類別、給特定的好友發送信息,以及製做微信機器人等。
本文的代碼已經上傳到 github 上:
https://github.com/ccc013/Python_Notes/tree/master/Projects/wechatProjects/itchat
也能夠按以下操做獲取代碼:
1.關注公衆號「機器學習與計算機視覺」
2.在公衆號後臺回覆「itchat",便可獲取代碼
參考:
歡迎關注個人微信公衆號--機器學習與計算機視覺,或者掃描下方的二維碼,你們一塊兒交流,學習和進步!
往期精彩推薦
機器學習系列
Github項目 & 資源教程推薦
本文分享自微信公衆號 - 算法猿的成長(AI_Developer)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。