一、好友地域詞雲
我們的好友都來自五湖四海,我們可以利用python的強大的數據庫來實現對好友地域的統計
工具:wxpy庫,wordcloud庫,matplotlib庫,openpyxl庫,pandas庫,numpy庫。
1、首先實現對微信的登陸與獲取好友數據操作
代碼:
#引入微信登陸接口 from wxpy import * #獲取登錄二維碼 bot = Bot(cache_path = True) #獲取微信朋友的基本數據 friend_all = bot.friends() #建立一個二維列表,存儲基本好友信息 lis = [['NickName','Sex','City','Province','Signature','HeadImgUrl','HeadImgFlag']] #把好有特征數據保存為列表 for a_friend in friend_all: NickName = a_friend.raw.get('NickName', None) Sex = {1:"男", 2:"女", 0:"其它"}.get(a_friend.raw.get('Sex', None), None) City = a_friend.raw.get('City', None) Province = a_friend.raw.get('Province', None) Signature = a_friend.raw.get('Signature', None) HeadImgUrl = a_friend.raw.get('HeadImgUrl', None) HeadImgFlag = a_friend.raw.get('HeadImgFlag', None) list_0 = [NickName, Sex, City, Province, Signature, HeadImgUrl, HeadImgFlag] lis.append(list_0)
運行結果:
此時彈出了二維碼,掃碼登陸即可自動獲取好友數據
2、將好友數據保存為xlsx文件
方便worldcloud庫進行處理
代碼:
#把列表轉換為 xlsx 表格 def list_to_xlsx(filename, list): import openpyxl wb = openpyxl.Workbook() sheet = wb.active sheet.title = 'Friends' file_name = filename + '.xlsx' for i in range(0, len(list)): for j in range(0, len(list[i])): sheet.cell(row = i+1, column = j+1, value = str(list[i][j])) wb.save(file_name) print("讀寫數據成功") #把列表生成表格 list_to_xlsx('wechat_friend', lis)
運行結果:
生成了一個xlsx文件
3、生成詞雲
利用worldcloud庫生成一個詞雲
代碼:
from wordcloud import WordCloud import matplotlib.pyplot as plt import pandas as pd from pandas import read_excel import numpy as np df = read_excel('wechat_friend.xlsx') #使用 WordCloud 生成詞雲 word_list = df['City'].fillna('0').tolist() new_text = ' '.join(word_list) wordcloud = WordCloud(font_path='msyh.ttc', background_color = 'white').generate(new_text) plt.imshow(wordcloud) plt.axis("off") plt.show() #使用 pyecharts 生成詞雲 from pyecharts import WordCloud city_list = df['City'].fillna('').tolist() count_city = pd.value_counts(city_list) name = count_city.index.tolist() value = count_city.tolist() wordcloud = WordCloud(width=1300,height=620) wordcloud.add("",name,value,word_size_range=[20,100]) #wordcloud.show_config() #wordcloud.render(r'D:\wc.html') wordcloud.render('wordcloud.html') #將好友展示在地圖上 from pyecharts import Map province
運行結果:
二、創建微信機器人
工具:requests模塊,itchat模塊
然后我們去茉莉機器人上申請api接口http://www.itpk.cn
代碼:
#-*- coding:utf-8 -*- import itchat import requests def get_response(msg): apiurl = 'http://i.itpk.cn/api.php' //moli機器人的網址 data={ "question": msg, //獲取到聊天的文本信息 "api_key": "9ddf52cacd0ef429d1c63bf411b9bed6", "api_secret": "n4gxkdyckd7p" } r=requests.post(apiurl,data=data) //構造網絡請求 return r.text @itchat.msg_register(itchat.content.TEXT) //好友消息的處理 def print_content(msg): return get_response(msg['Text']) @itchat.msg_register([itchat.content.TEXT], isGroupChat=True) //群消息的處理 def print_content(msg): return get_response(msg['Text']) itchat.auto_login(True) //自動登錄 itchat.run() //啟動聊天機器人
運行登陸即可