【Python】pythonを利用して微信の友人infoを這い出す


前言今日スタジオで勉强していた时、偶然ある公众号に「pythonで自分の微信の友达に登った」とプッシュされました.自分もpythonを勉强している过程なので、いっそ手元のこと仕事を中断して、点を入れて见て、操作して、itchatモジュールを勉强して、関连资料を调べていくつかの开発をしました.
#取付itchat筆者はpipキットを使用してインストールを行い、pip install itchatインストールが完了したらpythonに入ってimport itchatに書き込んでみたが、インストールに成功したというヒントは何もなかった.
#微信の友達の男女の割合を統計する
#-*- coding:utf-8 -*-
#           
import itchat
import re
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud,ImageColorGenerator
import numpy as np
import PIL.Image as Image
from os import path
from scipy.misc import imread	

#    ,        ,       
itchat.auto_login()		

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

#        
male = female = other = 0

#      
for i in friends[1:]:
	#            , 1, 2,  3
	sex = i['Sex']
	if sex == 1:
		male += 1
	elif sex == 2:
		female +=1
	else:
		other +=1

total = len(friends[1:])

print('    :%.2f%%' % (float(male)/total*100) + '
' + ' :%.2f%%' % (float(female)/total*100) + '
' + ' :%.2f%%' % (float(other)/total*100) + '
' )

#友達の顔を捕まえてパズル
# -*- coding:utf-8 -*-
#      
import itchat
import os
import PIL.Image as Image
from os import listdir
import math

#  
itchat.auto_login(enableCmdQR=True)
#           
friends = itchat.get_friends(update=True)[0:]
#        
user = friends[0]["UserName"]
#     
print(user)
#             
os.mkdir(user)

num = 0
#      ,     
for i in friends:
	img = itchat.get_head_img(userName=i["UserName"])
	fileImage = open(user + "/" + str(num) + ".jpg",'wb')
	fileImage.write(img)
	fileImage.close()
	num += 1

pics = listdir(user)
numPic = len(pics)
print(numPic)
eachsize = int(math.sqrt(float(640 * 640) / numPic))
print(eachsize)
numline = int(640 / eachsize)
toImage = Image.new('RGBA', (640, 640))
print(numline)

x = 0
y = 0

for i in pics:
	try:
		#    
		img = Image.open(user + "/" + i)
	except IOError:
		print("Error:              ")
	else:
		#    
		img = img.resize((eachsize, eachsize), Image.ANTIALIAS)
		#    
		toImage.paste(img, (x * eachsize, y * eachsize))
		x += 1
		if x == numline:
			x = 0
			y += 1

#        
toImage.save(user + ".BMP")
itchat.send_image(user + ".BMP", 'filehelper')


#友人の署名情報を取得し、ワードクラウド図を作成
#        
siglist = []

#      
for i in friends:
	#    
	signature = i['Signature'].strip().replace('span','').replace('class','').replace('emoji','')
	rep = re.compile('1f\d+\w*|[<>/=]')
	signature = rep.sub('',signature)
	siglist.append(signature)
	
#         text 
text = ''.join(siglist)

#      
textfile = open('info.txt','w')
textfile.write(text)
text_from_file_with_apath = open('./info.txt').read()
wordlist = jieba.cut(text_from_file_with_apath, cut_all = True)
word_space_split = " ".join(wordlist)

#  
coloring = plt.imread('./haha.jpg')
#        
my_wordcloud = WordCloud(background_color='white',
						max_words=2000,
						mask=coloring,
						max_font_size=100,
						random_state=42,						font_path='/Library/Fonts/Microsoft/SimHei.ttf').generate(word_space_split)
						
image_colors = ImageColorGenerator(coloring)
#    
plt.imshow(my_wordcloud)
plt.axis('off')
plt.show()

#     
my_wordcloud.to_file(path.join(d, "  .png"))

#チャットロボットの作成
#-*- coding=utf8 -*-
#      
import requests
import itchat
from wxpy import *

#  *       api key,   http://www.tuling123.com    
KEY = '***********************'

def get_response(msg):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {
        'key'    : KEY,
        'info'   : msg,
        'userid' : 'wechat-robot',
    }
    try:
        r = requests.post(apiUrl, data=data).json()
        return r.get('text')
    except:
        return
        
#             
@itchat.msg_register(itchat.content.TEXT)
#    
#@itchat.msg_register('Text', isGroupChat = True)

def tuling_reply(msg):
    defaultReply = 'I received: ' + msg['Text']
    reply = get_response(msg['Text'])
    #          
    return reply or defaultReply

    #busy         ,            ,    return busy
    #busy = '  ,      ,          ,              。'.decode('utf-8')
    #return busy
     
itchat.auto_login(hotReload=True)
itchat.run()

#冒頭のツイートについてまとめると、ツイートに表示される作成語雲図の機能に欠陥があるようで、実行後は背景色のみが表示され、文字は表示されませんでした.この文章では,語雲図の作成ロジック(複雑と言うべき)を修正し,最後の雲図が正常に表示された.
今日学習した内容はitchatモジュールの氷山の一角にすぎず、itchatモジュールには多くの機能がよく使われている.
itchat開発ドキュメント:http://itchat.readthedocs.io/zh/latest/