The original link: mp.weixin.qq.com/s/4EXgR4Gkr…
“Itchat” is an open source personal interface of wechat. Today, we will use itchat to crawl the information of our friends on wechat. The three graphs are “Wechat friends’ profile picture Mosaic”, “Gender Statistics” and “Personality signature Statistics”.
“Wechat friends’ Profile picture Mosaic”
“Gender Chart”
“Personality Signature Chart”
The installation
pip3 install itchat
Copy the code
Main methods used: Itchat.get_friends () returns a complete list of friends. Each friend is a dictionary. The first item is the user’s account information. Get_friends (update=True) itchat.get_head_img(userName=””
Spliced photos of wechat friends’ profile pictures
Get_head_img gets each friend’s profile picture, saves the file, and splits the profile picture into a larger image. Get your friend’s profile picture first:
def headImg():
itchat.login()
friends = itchat.get_friends(update=True)
# itchat.get_head_img() retrieves the avatar binary and writes it to a file, saving each avatar
for count, f in enumerate(friends):
# get avatar based on userName
img = itchat.get_head_img(userName=f["UserName"])
imgFile = open("img/" + str(count) + ".jpg"."wb")
imgFile.write(img)
imgFile.close()
Copy the code
The img folder must be created in the same directory in advance, otherwise the error “No such file or directory” will be reported. The img folder is used to save the profile picture, traverse the friends list, and name the profile picture according to the subscript count.
The next step is to splice the heads
Shuffle (IMgs) to shuffle images through a folder
Average each profile picture with a large picture of 640*640, calculate the length and width of each small square picture, compress the profile picture, splice the picture, fill up the line, splice the picture with line breaks, and increase the area of the large picture appropriately if there are many friends’ profile pictures. The specific code is as follows:
def createImg():
x = 0
y = 0
imgs = os.listdir("img")
random.shuffle(imgs)
# create a 640*640 image to fill each small image
newImg = Image.new('RGBA'), (640, 640)Square root of math.sqrt() to calculate the width and height of each small image.
width = int(math.sqrt(640 * 640 / len(imgs)))
# number of images per line
numLine = int(640 / width)
for i in imgs:
img = Image.open("img/" + i)
# Zoom out
img = img.resize((width, width), Image.ANTIALIAS)
# Splice picture, line full, line break splice
newImg.paste(img, (x * width, y * width))
x += 1
if x >= numLine:
x = 0
y += 1
newImg.save("all.png")
Copy the code
Friend profile picture forming, profile picture is randomly shuffled splicing
Gender chart
Similarly, itchat.login() login to obtain the information of friends, and determine the gender according to the Sex field. 1 represents male (man), 2 represents female (women), and 3 is unknown.
def getSex():
itchat.login()
friends = itchat.get_friends(update=True)
sex = dict()
for f in friends:
if f["Sex"] = = 1:# male
sex["man"] = sex.get("man"+ 1, 0)elif f["Sex"] = = 2:Female #
sex["women"] = sex.get("women"+ 1, 0)else: # the unknown
sex["unknown"] = sex.get("unknown"+ 1, 0)# Bar chart display
for i, key in enumerate(sex):
plt.bar(key, sex[key])
plt.show()
Copy the code
Bar chart of sex statistics
Personality signature statistics chart
The Signature field is the Signature of the friend. Save the Signature to the.txt file. Some of the signatures contain emojis and other words that will become emojis, and replace them with special symbols.
def getSignature():
itchat.login()
friends = itchat.get_friends(update=True)
file = open('sign.txt'.'a', encoding='utf-8')
for f in friends:
signature = f["Signature"].strip().replace("emoji"."").replace("span"."").replace("class"."")
# regular match
rec = re.compile("1f\d+\w*|[<>/=]")
signature = rec.sub("", signature)
file.write(signature + "\n")
Copy the code
TXT file to write the personality signatures of all friends, use wordcloud package to generate wordcloud map, PIP install wordcloud can also use jieba word to generate word map, do not use word partition is sentence display. To use jieba, the max_font_size attribute can be increased appropriately, such as 100. Deactivate deactivate deactivate deactivate deactivate deactivate deactivate deactivate
# Generate word cloud
def create_word_cloud(filename):
Read the contents of the file
text = open("{}.txt".format(filename), encoding='utf-8').read()
# Stutter
# wordlist = jieba.cut(text, cut_all=True)
# wl = " ".join(wordlist)
# Set the word cloud
wc = WordCloud(
# Set the background color
background_color="white".# set the maximum number of word clouds to display
max_words=2000,
# this font in the computer font, window in C: \ Windows \ Fonts \, optional under MAC/System/Library/Fonts/PingFang TTC Fonts
font_path='C:\\Windows\\Fonts\\simfang.ttf',
height=500,
width=500,
Set the maximum font size
max_font_size=60,
# set how many randomly generated states there are, i.e. how many color schemes there are
random_state=30,
)
myword = wc.generate(text) If stuttering is used, use WL instead of text to create a word cloud
# Show word cloud
plt.imshow(myword)
plt.axis("off")
plt.show()
wc.to_file('signature.png') # Save the word cloud
Copy the code
Sentence figure
The word cloud map produced by using jieba
Itchat in addition to the above information, there are provinces and cities and other information can be captured, in addition to the robot automatic chat and other functions, here is not an overview.
Finally, attach github address: github.com/taixiang/it…
Welcome to pay attention to my blog: blog.manjiexiang.cn/ welcome to pay attention to micro signal: Spring breeze ten miles better to know you