1.用 Python 實作微信好友性別及位置資訊統計
這里使用的python3+wxpy庫+Anaconda(Spyder)開發,如果你想對wxpy有更深的了解請查看:wxpy: 用 Python 玩微信
# -*- coding: utf-8 -*-
"""
微信好友性別及位置資訊
這里要注意:不管你是為了Python就業還是興趣愛好,記住:專案開發經驗永遠是核心,如果你沒有2020最新python入門到高級實戰視頻教程,可以去小編的Python交流.裙 :七衣衣九七七巴而五(數字的諧音)轉換下可以找到了,里面很多新python教程專案,還可以跟老司機交流討教!
#匯入模塊
from wxpy import Bot
'''Q
微信機器人登錄有3種模式,
(1)極簡模式:robot = Bot()
(2)終端模式:robot = Bot(console_qr=True)
(3)快取模式(可保持登錄狀態):robot = Bot(cache_path=True)
'''
#初始化機器人,選擇快取模式(掃碼)登錄
robot = Bot(cache_path=True)
#獲取好友資訊
robot.chats()
#robot.mps()#獲取微信公眾號資訊
#獲取好友的統計資訊
Friends = robot.friends()
print(Friends.stats_text())
復制代碼
效果圖(來自筆主盆友圈):
2.用 Python 實作聊天機器人
這里使用的python3+wxpy庫+Anaconda(Spyder)開發,需要提前去圖靈官網創建一個屬于自己的機器人然后得到apikey,
- 使用圖靈機器人自動與指定好友聊天
讓室友幫忙測驗發現發送表情發送文字還能回應,但是發送圖片可能不會回復,猜應該是我們申請的圖靈機器人是最初級的沒有加圖片識別功能,
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 19:09:05 2018
@author: Snailclimb
@description使用圖靈機器人自動與指定好友聊天
"""
from wxpy import Bot,Tuling,embed,ensure_one
bot = Bot()
my_friend = ensure_one(bot.search('鄭凱')) #想和機器人聊天的好友的備注
tuling = Tuling(api_key='你申請的apikey')
@bot.register(my_friend) # 使用圖靈機器人自動與指定好友聊天
def reply_my_friend(msg):
tuling.do_reply(msg)
embed()
復制代碼
- 使用圖靈機器人群聊
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 18:55:04 2018
@author: Administrator
"""
from wxpy import Bot,Tuling,embed
bot = Bot(cache_path=True)
my_group = bot.groups().search('群聊名稱')[0] # 記得把名字改成想用機器人的群
tuling = Tuling(api_key='你申請的apikey') # 一定要添加,不然實作不了
@bot.register(my_group, except_self=False) # 使用圖靈機器人自動在指定群聊天
def reply_my_friend(msg):
print(tuling.do_reply(msg))
embed()
復制代碼
3.用 Python分析朋友圈好友性別分布(圖示展示)
這里沒有使用wxpy而是換成了Itchat操作微信,itchat只需要2行代碼就可以登錄微信,如果你想詳細了解itchat,請查看: itchat入門進階教程以及 itchat github專案地址 另外就是需要用到python的一個畫圖功能非常強大的第三方庫:matplotlib, 如果你想對matplotlib有更深的了解請查看我的博文:Python第三方庫matplotlib(詞云)入門與進階
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 17:09:26 2018
@author: Snalclimb
@description 微信好友性別比例
"""
import itchat
import matplotlib.pyplot as plt
from collections import Counter
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)
sexs = list(map(lambda x: x['Sex'], friends[1:]))
counts = list(map(lambda x: x[1], Counter(sexs).items()))
labels = ['Male','FeMale', 'Unknown']
colors = ['red', 'yellowgreen', 'lightskyblue']
plt.figure(figsize=(8, 5), dpi=80)
plt.axes(aspect=1)
plt.pie(counts, # 性別統計結果
labels=labels, # 性別展示標簽
colors=colors, # 餅圖區域配色
labeldistance=1.1, # 標簽距離圓點距離
autopct='%3.1f%%', # 餅圖區域文本格式
shadow=False, # 餅圖是否顯示陰影
startangle=90, # 餅圖起始角度
pctdistance=0.6 # 餅圖區域文本距離圓點距離
)
plt.legend(loc='upper right',)
plt.title('%s的微信好友性別組成' % friends[0]['NickName'])
plt.show()
復制代碼
效果圖(來自筆主盆友圈):
4.用 Python分析朋友圈好友的簽名
需要用到的第三方庫:
numpy:本例結合wordcloud使用
jieba:對中文驚進行分詞
PIL: 對影像進行處理(本例與wordcloud結合使用)
snowlp:對文本資訊進行情感判斷
wordcloud:生成詞云 matplotlib:繪制2D圖形
# -*- coding: utf-8 -*-
"""
朋友圈朋友簽名的詞云生成以及
簽名情感分析
"""
import re,jieba,itchat
import jieba.analyse
import numpy as np
from PIL import Image
from snownlp import SnowNLP
from wordcloud import WordCloud
import matplotlib.pyplot as plt
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)
def analyseSignature(friends):
signatures = ''
emotions = []
for friend in friends:
signature = friend['Signature']
if(signature != None):
signature = signature.strip().replace('span', '').replace('class', '').replace('emoji', '')
signature = re.sub(r'1f(\d.+)','',signature)
if(len(signature)>0):
nlp = SnowNLP(signature)
emotions.append(nlp.sentiments)
signatures += ' '.join(jieba.analyse.extract_tags(signature,5))
with open('signatures.txt','wt',encoding='utf-8') as file:
file.write(signatures)
# 朋友圈朋友簽名的詞云相關屬性設定
back_coloring = np.array(Image.open('alice_color.png'))
wordcloud = WordCloud(
font_path='simfang.ttf',
background_color="white",
max_words=1200,
mask=back_coloring,
max_font_size=75,
random_state=45,
width=1250,
height=1000,
margin=15
)
#生成朋友圈朋友簽名的詞云
wordcloud.generate(signatures)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
wordcloud.to_file('signatures.jpg')#保存到本地檔案
# Signature Emotional Judgment
count_good = len(list(filter(lambda x:x>0.66,emotions)))#正面積極
count_normal = len(list(filter(lambda x:x>=0.33 and x<=0.66,emotions)))#中性
count_bad = len(list(filter(lambda x:x<0.33,emotions)))#負面消極
labels = [u'負面消極',u'中性',u'正面積極']
values = (count_bad,count_normal,count_good)
plt.rcParams['font.sans-serif'] = ['simHei']
plt.rcParams['axes.unicode_minus'] = False
plt.xlabel(u'情感判斷')#x軸
plt.ylabel(u'頻數')#y軸
plt.xticks(range(3),labels)
plt.legend(loc='upper right',)
plt.bar(range(3), values, color = 'rgb')
plt.title(u'%s的微信好友簽名資訊情感分析' % friends[0]['NickName'])
plt.show()
analyseSignature(friends)
復制代碼
效果圖(來自筆主盆友圈):
最后注意:不管你是為了Python就業還是興趣愛好,記住:專案開發經驗永遠是核心,如果你沒有2020最新python入門到高級實戰視頻教程,可以去小編的Python交流.裙 :七衣衣九七七巴而五(數字的諧音)轉換下可以找到了,里面很多新python教程專案,還可以跟老司機交流討教!
本文的文字及圖片來源于網路加上自己的想法,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/151734.html
標籤:Python
