1. 程式人生 > >python+itchat 爬取微信好友資訊

python+itchat 爬取微信好友資訊

專案環境

語言:Python3
編輯器:Pycharm
導包:matplotlib、numpy、wordCloud、PIL、jieba、itchat

前言

近朱者赤,近墨者黑。微信已成為我們生活中必不可少的通訊社交工具,朋友圈一個分享我們生活的平臺,接下來先拿我的微信好友開刀,一起看看我們的圈子裡都有哪些有趣的事。

爬取性別

itchat.get_friends() 返回完整的好友列表,每個好友為一個字典, 其中第一項為本人的賬號資訊;傳入 update=True, 將更新好友列表並返回。sex=1為男性,sex=2為女性。其他的就是沒填性別的。

def draw_sex
(): itchat.login() text = dict() friends = itchat.get_friends(update=True)[0:] male = "male" female = "female" other = "other" for i in friends[1:]: sex = i['Sex'] if sex == 1: text[male] = text.get(male, 0) + 1 elif sex == 2: text[
female] = text.get(female, 0) + 1 else: text[other] = text.get(other, 0) + 1 for key in text.keys(): plt.bar(key, text[key]) plt.xlabel('sex') plt.ylabel('rate') plt.title("Gender histogram") plt.savefig("sex.png") # 儲存圖片 plt.ion() plt.pause(5) plt.
close() # 圖片顯示5s,之後關閉

在程式碼裡通過一個 for 迴圈,把獲取到的資料通過 for 迴圈儲存到 text 字典裡。然後再通過 plt 庫函式畫出性別柱狀圖。

生成簽名的詞雲圖

1.獲取好友簽名信息
Signature欄位是好友的簽名,在這裡使用的是結巴分詞,將簽名儘可能的分成更多的詞,將其儲存到sign.txt檔案中,由於有些簽名包含一些表情,抓取會變成 emoji、span、class 等等這些無關的詞,將這些含有特殊符號的替換掉。

def get_signature():
    itchat.login()
    siglist = []
    friends = itchat.get_friends(update=True)[1:]
    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 = "".join(siglist)
    with io.open('sign.txt', 'a', encoding='utf-8') as f:
        signature_list = jieba.cut(text, cut_all=True)# 全模式,把文字分成儘可能多的詞
        signature_space_split = " ".join(signature_list)
        f.write(signature_space_split)
        f.close()

2.繪製詞雲圖
使用wordcloud生成詞雲圖,讀取sign.txt中的簽名詞,選擇一張背景圖china.jpg,程式碼如下:

def draw_word_cloud():
    text = open(u'sign.txt', encoding='utf-8').read()
    coloring = np.array(Image.open('china.jpg'))
    wordcloud = WordCloud(
        # 設定背景顏色
        background_color="white",
        # 設定最大顯示的詞雲數
        max_words=2000,
        mask=coloring,
        # 設定字型最大值
        max_font_size=60,
        # 設定有多少種隨機生成狀態,即有多少種配色方案
        random_state=42,
        scale=2,
        # 這種字型都在電腦字型中,window在C:\Windows\Fonts\下,
        font_path='C:/Windows/Fonts/simkai.ttf').generate(text)
    image_colors = ImageColorGenerator(coloring)
    plt.imshow(wordcloud.recolor(color_func=image_colors))
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()
    wordcloud.to_file('signature.png')  # 把詞雲儲存下

微信好友頭像拼接圖

1.獲取好友影象
獲取好友資訊,get_head_img拿到每個好友的頭像,在同目錄下新建了資料夾img用於儲存好友影象,根據下標i命名頭像。

def get_head_img():
    itchat.login()
    friends = itchat.get_friends(update=True)
    for i, f in enumerate(friends):
        # 根據userName獲取頭像
        img = itchat.get_head_img(userName=f["UserName"])
        imgFile = open("img/" + str(i) + ".jpg", "wb")
        imgFile.write(img)
        imgFile.close()

2.好友影象拼接
遍歷img資料夾的圖片,用640*640的大圖來平均分每一張頭像,計算出每張正方形小圖的長寬,壓縮頭像,拼接圖片,一行排滿,換行拼接,具體程式碼如下:

# 頭像拼接圖
def create_img():
    x = 0
    y = 0
    imgs = os.listdir("img")
    # random.shuffle(imgs)將圖片順序打亂,
    random.shuffle(imgs)
    # 建立640*640的圖片用於填充各小圖片
    total_img = Image.new('RGBA', (640, 640))
    # math.sqrt()開平方根計算每張小圖片的寬高,
    width = int(np.math.sqrt(640 * 640 / len(imgs)))
    # 每行圖片數
    row_num = int(640 / width)

    for i in imgs:
        try:
            img = Image.open("img/" + i)
            # 縮小圖片
            img = img.resize((width, width), Image.ANTIALIAS)
            # 拼接圖片,一行排滿,換行拼接
            total_img.paste(img, (x * width, y * width))
            x += 1
            if x >= row_num:
                x = 0
                y += 1
        except IOError:
            print("img/ %s can not open" % (i))
    total_img.save("result.png")

效果圖

在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述
更多內容歡迎大家關注
在這裡插入圖片描述