How to Analyze Your WeChat Friends with Python: Gender, Avatar, Signature & Location Insights
This tutorial shows how to use Python libraries such as itchat, jieba, matplotlib, snownlp, and Tencent Youtu to fetch WeChat friend data and produce visual analyses of gender distribution, avatar face detection and tags, signature word clouds and sentiment, and geographic location, all illustrated with charts and code examples.
Data Analysis Overview
The article demonstrates a step‑by‑step Python workflow for extracting WeChat friend information and visualizing four dimensions: gender, avatar, signature, and location.
Required Third‑Party Modules
itchat – wrapper for the WeChat web API to obtain friend data.
jieba – Chinese word segmentation for text processing.
matplotlib – charting library for bar, pie, and other plots.
snownlp – sentiment analysis for Chinese text.
PIL – image handling.
numpy – numeric operations, used with the wordcloud module.
wordcloud – generation of word‑cloud images.
TencentYoutuyun – SDK for face detection and image‑tag extraction.
Login and Data Retrieval
itchat.auto_login(hotReload=True)
friends = itchat.get_friends(update=True)The friends object is a list of dictionaries; friends[1:] contains the actual contacts, each with fields such as Sex, HeadImgUrl, Signature, Province, and City.
1. Friend Gender Analysis
Gender values are 0 (Unknown), 1 (Male), and 2 (Female). The code extracts these values, counts each category, and draws a pie chart.
def analyseSex(friends):
sexs = list(map(lambda x: x['Sex'], friends[1:]))
counts = list(map(lambda x: x[1], Counter(sexs).items()))
labels = ['Unknow', 'Male', 'Female']
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(u"%s's WeChat Friend Gender Distribution" % friends[0]['NickName'])
plt.show()2. Friend Avatar Analysis
Avatars are downloaded via itchat.get_head_img. Tencent Youtu detects whether an avatar contains a face and extracts image tags. Results are shown with a pie chart for face usage and a word cloud for extracted tags.
def analyseHeadImage(friends):
basePath = os.path.abspath('.')
baseFolder = basePath + '\\HeadImages\\'
if not os.path.exists(baseFolder):
os.makedirs(baseFolder)
faceApi = FaceAPI()
use_face, not_use_face = 0, 0
image_tags = ''
for index in range(1, len(friends)):
friend = friends[index]
imgFile = baseFolder + '\\Image%s.jpg' % str(index)
imgData = itchat.get_head_img(userName=friend['UserName'])
if not os.path.exists(imgFile):
with open(imgFile, 'wb') as file:
file.write(imgData)
time.sleep(1)
if faceApi.detectFace(imgFile):
use_face += 1
else:
not_use_face += 1
tags = faceApi.extractTags(imgFile)
image_tags += ','.join([t['tag_name'] for t in tags])
labels = [u'使用人脸头像', u'不使用人脸头像']
counts = [use_face, not_use_face]
colors = ['red', 'yellowgreen']
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(u"%s's WeChat Friend Face Avatar Usage" % friends[0]['NickName'])
plt.show()
# Word cloud for tags
back_coloring = np.array(Image.open('face.jpg'))
wc = WordCloud(font_path='simfang.ttf', background_color='white',
max_words=1200, mask=back_coloring, max_font_size=75,
random_state=45, width=800, height=480, margin=15)
wc.generate(image_tags)
plt.imshow(wc)
plt.axis('off')
plt.show()3. Friend Signature Analysis
Signatures are processed with jieba for keyword extraction (word cloud) and SnowNLP for sentiment scoring. The code builds a combined word cloud and a bar chart of sentiment categories.
def analyseSignature(friends):
signatures = ''
emotions = []
pattern = re.compile("1f\d.+")
for friend in friends:
signature = friend['Signature']
if signature:
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))
# Word cloud
back_coloring = np.array(Image.open('flower.jpg'))
wc = WordCloud(font_path='simfang.ttf', background_color='white',
max_words=1200, mask=back_coloring, max_font_size=75,
random_state=45, width=960, height=720, margin=15)
wc.generate(signatures)
plt.imshow(wc)
plt.axis('off')
plt.show()
# Sentiment bar chart
count_good = len(list(filter(lambda x: x>0.66, emotions)))
count_normal = len(list(filter(lambda x: 0.33<=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.bar(range(3), values, color='rgb')
plt.xticks(range(3), labels)
plt.xlabel(u'情感判断')
plt.ylabel(u'频数')
plt.title(u"%s's WeChat Friend Signature Sentiment Analysis" % friends[0]['NickName'])
plt.show()4. Friend Location Analysis
Province and City fields are extracted and written to a CSV file, which can be imported into Baidu BDP for map visualization.
def analyseLocation(friends):
headers = ['NickName','Province','City']
with open('location.csv','w',encoding='utf-8',newline='') as csvFile:
writer = csv.DictWriter(csvFile, headers)
writer.writeheader()
for friend in friends[1:]:
row = {'NickName': friend['NickName'],
'Province': friend['Province'],
'City': friend['City']}
writer.writerow(row)Conclusion
The article shows a complete, reproducible pipeline for visualizing personal WeChat friend data, illustrating how simple Python tools can reveal gender ratios, avatar usage patterns, common signature keywords, sentiment distribution, and geographic concentration, while emphasizing that visualization is a means to gain insight rather than an end in itself.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
