[Python] get friends itchat Log in micro-signed the letter and generate a word cloud

Know almost see in the article on how to use itchat Statistics Friends proportion of men and women and the use of micro-channel plt histogram generation and access to micro-letter friends and generate a signature word cloud article https://zhuanlan.zhihu.com/p/36361397 , I feel very under Interestingly, the study did as found in the original article did not specify how to use library resources to install and use no explanation, here under the detailed records.

Used in this section of the library and installation

itchat      

Micro-channel related operations, cmd the 'pip install itchat'

pillow (pills)    

Image used, cmd in the 'pip install pillow'

re       

Regular Expressions

wordcloud    

Word cloud, using pip installation has been prompted Built wrong time, so https://www.lfd.uci.edu/~gohlke/pythonlibs/ find wordcloud corresponding version, and then 'pip install wheel path \ *. Whl'

jieba

Thesaurus points, can be split in the word string, the cmd 'pip install jieba'

numpy

plt used, cmd the 'pip install numpy'

Reference Library

 1 #!/user/bin/python
 2 ##coding=utf-8
 3 import itchat
 4 from itchat.content import *
 5 import numpy as np
 6 from matplotlib import pyplot as plt
 7 import re
 8 from wordcloud import WordCloud
 9 from wordcloud import ImageColorGenerator
10 import os
11 import io
12 import jieba
13 from PIL import Image

Login obtain micro letter friends proportion of men and women

 1 itchat.login()
 2 text=dict()
 3 friends = itchat.get_friends(update=True)[0:]
 4 male="male"
 5 female="female"
 6 other="other"
 7 for i in friends[1:]:
 8     sex = i['Sex']
 9     if sex == 1:
10         text[male] = text.get(male, 0) + 1
11     elif sex == 2:
12         text [FEMALE] = text.get (FEMALE, 0). 1 +
 13 is      the else :
 14          text [OTHER] = text.get (OTHER, 0). 1 +
 15 Total = len (Friends [. 1 :])
 16  Print (Total)
 . 17  Print ( " male friend:% .2f %% " % (a float (text [mALE]) / Total * 100) + " \ n- " + 
 18 is      " female friend:% .2f %% " % (a float (text [ FEMALE]) / Total * 100) + " \ n- " +
 . 19      " unknown friends gender:% .2f %% " % (a float (text [OTHER]) / Total * 100))

The proportion of men and women drawn using PLT histogram

1 def draw(datas):
2     for key in datas.keys():
3         plt.bar(key,datas[key])
4 
5     plt.legend()
6     plt.xlabel('sex')
7     plt.ylabel('rate')
8     plt.title("Gender of Alfred's friends")
9     plt.show()

Friends crawling signature and save it to a file

 1 def parse_signature():
 2     itchat.login()
 3     siglist = []
 4     friends = itchat.get_friends(update=True)[1:]
 5     for i in  friends:
 6         signature = i["Signature"].strip().replace("span","").replace("class","").replace("emoji","")
 7         rep = re.compile("lf\d+\w|[<>/=]")
 8         signature = rep.sub("",signature)
 9         siglist.append(signature)
10     text = "".join(siglist)
11     with io.open('text.txt', 'a', encoding='utf-8') as f:
12         wordlist = jieba.cut(text, cut_all=True)
13         word_space_split = " ".join(wordlist)
14         f.write(word_space_split)
15         f.close()

Parses the file and draw the word cloud

Prepare a picture (8.jpg) into the current directory, font resources ready (DroidSansFallbackFull.ttf), you can search using everything in their computers take over a font resource use, into the current directory, if there is no will question of resources.

1 def draw_signature():
2     text = open(u'text.txt', encoding='utf-8').read()
3     coloring = np.array(Image.open('8.jpg'))
4     my_wordcloud = WordCloud(background_color="white", max_words=2000,mask=coloring, max_font_size=300,random_state=42,scale=2,font_path="DroidSansFallbackFull.ttf").generate(text)
5     image_colors = ImageColorGenerator(coloring)
6     plt.imshow(my_wordcloud.recolor(color_func=image_colors))
7     plt.imshow(my_wordcloud)
8     plt.axis("off")
9     plt.show()

Episode: micro-channel auto-reply

 1 @itchat.msg_register([PICTURE,TEXT])
 2 def simple_reply(msg):
 3     if msg['Type'] == TEXT:
 4         ReplyContent = 'I received message: '+msg['Content']
 5     if msg['Type'] == PICTURE:
 6         ReplyContent = 'I received picture: '+msg['FileName']
 7     itchat.send_msg('nice to meet you',msg['FromUserName'])
 8 
 9 itchat.auto_login()
10 itchat.run()

Finish

For more details, go https://zhuanlan.zhihu.com/p/36361397

reference

https://itchat.readthedocs.io/zh/latest/

https://zhuanlan.zhihu.com/p/36361397

Guess you like

Origin www.cnblogs.com/huangsitao/p/10961867.html