python 之词云

1.爬取词源网页

在这我是爬取的自己博客的一些标签

1
2
3
4
5
6
7
8
9
10
11
12
13
14

#获取html
def getHtml():
url = 'https://zjqian.github.io/tags/index.html'
res = requests.get(url)
return res.text

#通过BeautifulSoup解析网页,得到标签
def getContent():
soup = BeautifulSoup(getHtml(),'lxml')
text = ''
for item in soup.find('div', class_='tag-cloud-tags'):
text += item.string
return text

2.生成词云

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

def getWordCloud():
d = path.dirname(__file__)
#词云所依照的图片格式
coloring = np.array(Image.open(path.join(d, "WordArt.png")))
#设置WordCloud属性
wc = WordCloud(background_color="white",
max_words=2000,
mask=coloring,
max_font_size=50,
random_state=42,
font_path='fangsong_GB2312.ttf')

wc.generate(getContent())
# 设置词的颜色
color_to_words = {
# 使用RGB来设置词的颜色
}
# 设置词默认的颜色
default_color = "black"
grouped_color_func = GroupedColorFunc(color_to_words, default_color)
# 设置词云的颜色
wc.recolor(color_func=grouped_color_func)

# create coloring from image
# image_colors = ImageColorGenerator(coloring)
wc.to_file("路径/word-cloud.png") # 保存图片
plt.figure()
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.show()

3.词云效果图:

由于词源有点少,所以图片中的熊猫有点不太清楚,可它真的是熊猫

这是源图片

对比一下,第二张是源图片

-------------本文结束感谢您的阅读-------------
分享使我快乐!