40

520 | 程序员10分钟硬核表白教程!

 4 years ago
source link: https://www.tuicool.com/articles/BVfI7rU
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

by2QBvn.jpg!web

今天,是“520”

也是传说中的“表白日”。

Love makes the world go round !

忙于Coding(sheng fa)的程序员们    

苦于如何表白?!

没关系,我们已经帮你想好了!

今天来点程序员的硬核技能——

用Python为Ta定制专属“词云”! 

:musical_note: 听首歌~让我们带着愉悦的心情,一起来准备“表白”吧!)

“词云”的制作远没有大家想象中的那么难。

不论你有没有学过Python,相信我!就算是文科生,也是可以按照以下步骤完成操作的!

01

环境准备

软件环境:Anaconda3.5(下载链接可后台回复“Anaconda”)
系统:macOS
文本:jdcdeve.txt

图片:heart.jpg

主要包:jieba、wordcloud

☞. 打开Anaconda,然后选择Jupyter:

FJRFz2F.jpg!web

☞.点击New按钮,新建一个笔记本(Notebook)。在Notebook里选择Python3选:

6BvQVrB.jpg!web

☞. 安装wordcloud 和 jieba 两个库只要在命令行输入以下代码即可:

1pip install wordcloud
2pip install jieba

02

代码分析

接下来,就可以输入以下代码来进行词云生成了:

 1 from os import path
 2 from PIL import Image
 3 import numpy as np
 4 import matplotlib.pyplot as plt
 5 import os
 6 import chardet
 7 import jieba
 8
 9
10from wordcloud import WordCloud, STOPWORDS
11from pip._vendor.pyparsing import WordStart
12
13# 获取当前项目文件的路径
14d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
15fontpath='SourceHanSerifK-Light.otf'
16
17# 读取要分析的文本
18text = open(path.join(d, 'jdcdeve.txt'), 'r', encoding='UTF-8').read()
19words = jieba.lcut(text)
20cuted  = ' '.join(words)
21
22# 读取背景图,进行分词
23heart_mask = np.array(Image.open(path.join(d, "heart.jpg")))
24
25stopwords = set(STOPWORDS)
26
27wc = WordCloud(font_path=fontpath, background_color="white", max_words=10000, mask=heart_mask,stopwords=stopwords, colormap = "RdBu")
28
29# 生成词云
30wc.generate(cuted)
31
32# 保存文件
33wc.to_file(path.join(d, "result.png"))
34
35# 画图云,显示
36plt.imshow(wc, interpolation='bilinear')
37plt.axis("off")
38plt.figure()
39plt.imshow(heart_mask, cmap=plt.cm.gray, interpolation='bilinear')
40plt.axis("off")
41plt.show()

输入完毕后,shift+enter键就可以看到结果啦!

(注:字体颜色的更换可参考 http://www.sthda.com/english/wiki/word-cloud-generator-in-r-one-killer-function-to-do-everything-you-need)

03

结果输出

如果 想要将生成图片中的文字换成心爱的Ta或你们共同的回忆,只需要在初始文本(如:jdcdeve.txt)里疯狂输入你想要呈现的文字,就能在最后生成图中出现了哦!

QJRnIz7.jpg!web

最后!

在这个特殊的日子,我们也要跟你表白一波!

感谢开发者们对“京东云开发者社区”一直的支持!

希望大家都可以有人爱,且有爱人!!!

X.O.X.O~

6BVB3uJ.png!web

:angel::angel::angel:

如果你还没到表白的阶段,也没关系!

让Ta开心,一定没错!

↓↓↓

世界微笑日 | 我们是!可以让你笑到合不上嘴的程序员

3Abumq6.gif


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK