avatarYeung WONG

总结

本文是一篇关于如何使用Python创建中文词云的教程,涵盖了从数据准备、词云设计到生成词云的全过程。

摘要

文章首先介绍了作者在尝试生成中文词云时遇到的资源不足问题,并以此为动机创作了这篇文章。作者提供了GitHub仓库和Kaggle链接,供读者参考和直接运行代码。接着,文章详细介绍了生成中文词云的三个步骤:

  1. 数据源(文本):作者使用香港高登论坛的帖子作为文本数据源,并指出中文文本需要使用jieba进行分词处理。

  2. 词云设计:包括形状、颜色和字体的选择。作者建议使用特定图片作为形状模板,提供了三种颜色选择方法,并强调了选择支持中文的字体的重要性。

  3. 生成词云:文章展示了如何使用WordCloud库生成词云,包括如何设置字体路径、背景颜色、最大词汇数量、遮罩图片、最大字体大小等参数,并且介绍了如何将生成的词云保存为图片和显示在屏幕上。

最后,作者总结了整篇教程,鼓励读者分享这篇文章,并提供了自己的网站和LinkedIn个人页面,以及其他相关文章的链接。

观点

  • 资源不足:中文词云生成的在线资源不多,且对于编程初学者来说不够全面。
  • 数据准备:使用现成的中文文本数据源,并通过jieba进行中文分词。
  • 设计重要性:词云的设计不仅仅是形状和颜色的选择,更是对中文字体支持的考虑。
  • 教学目的:文章旨在帮助读者掌握创建中文词云的技巧,并鼓励分享和学习。
  • 持续学习:作者计划发布更多类似的教学文章,鼓励读者持续关注和学习。

[Written in Chinese] Step-by-Step Chinese Word Cloud with Python

Chinese Word Cloud Example

When I am going to generate a word cloud in Chinese, I found there is less resource that can be relied on in the Internet and they are not comprehensive at all for a programming beginner to start working with. I know because I am one of the beginners. =) That’s why I have an idea to create this post. Since this is for Chinese Word Cloud, I think using Chinese to explain would be better and easier. For those who wants a post for generating English Word Cloud, leave a comment and let me know.

Here is the Github repository.

You can also copy and run the code directly on Kaggle.

Step 1 - Data Source (Text)

香港高登討論區 [ 高登 ](https://www.hkgolden.com/) 是香港一個著名而普及的網上論壇,不同年紀、性別或宗教的香港人也有人使用,高登所涉及的內容範圍很廣泛,上至財經資訊、時事消息,下至感情生活、娛樂新聞,籠統而言,高登就好像是香港的一個縮影。透過 word cloud 去分析高登上面的 posts,我們可以從中找出香港人最關心的時事議題、最喜愛的明星跟組合,最留意的股票動向,甚至是性方面的癖好等等。

高登不同的討論區

這次教學並不是 website scraping,所以我不打算詳細講解怎樣從高登討論區把 post 的內容 scrape 下來,各位可以使用自己想用的文字檔即可。

從高登娛樂台 scrape 的 example

而我這次教學會使用感情台的 posts 作為我 word cloud 的數據。

# name the word cloud data source as variable text
text = open('text.txt', 'r',encoding= 'UTF-8-sig').read()
沒有經過處理的文字檔

中文跟英文其中一個不一樣的地方就在於英文每個字中間會有空白格,但是中文並沒有,所以我們需要利用 jieba 的 tokenization 幫我們分詞。

import jieba
text = ' '.join(jieba.cut(text))
text
text 經 tokenize 後完成分詞

Step 2 - Word Cloud Design

處理好文字檔以後要做的就是構思想要的 word cloud design。簡單來說重點有三大方面 (形狀、顏色、字型 )。

  • 形狀

word cloud default 的形狀是長方形的,如果你想創作一個有趣形狀的 word cloud,你就需要準備一張圖片。例如我用了這張圖片:

特別形狀的圖片

溫馨提示,圖片是 PNG 檔,其中白色的部分是透明的。

from PIL import Image
import numpy as np
icon_path = 'icon.png'
icon = Image.open(icon_path)
mask = Image.new("RGB", icon.size, (255,255,255))
mask.paste(icon,icon)
mask = np.array(mask)
  • 顏色

文字顏色的選擇主要有三種: ( 三選一就行 )

i. 純色

def color_func(word, font_size, position, orientation, random_state=None, **kwargs):
    return tuple([255,255,255]) # RGB code of white color

ii. 根據 DIY 圖片本來的顏色

from wordcloud import ImageColorGenerator
color_func = ImageColorGenerator(mask)

iii. palettable.colorbrewer package 的 color set

先到 https://jiffyclub.github.io/palettable/colorbrewer/ 選擇想要的 color set ,總共有三組不同的類別,包括 diverging, qualitative 和 sequential ,例如我選取了sequential 組別當中的 YlGnBu_9。

Palettable Colorbrewer 其中一些 color set example
import random
from palettable.colorbrewer.sequential import YlGnBu_9 # choose the color set you like
def color_func(word, font_size, position, orientation, random_state=None, **kwargs):
    return tuple(YlGnBu_9.colors[random.randint(0,8)]) # we got 9 colors, so we generate random number from 0 to 8

以下是不同選擇的效果圖:

時事台 ( 純色 )
娛樂台 ( 根據 DIY 圖片的顏色 )
財經台 ( 使用了 palettable.colorbrewer.sequential 中的 YlGnBu_9 color set )
  • 字型

值得一提的是字型,因為這次我們使用的 wordcloud package default 所使用的字型只能夠顯示英文,所以如果希望 display 中文的話,就必需要,我重覆,是必需要準備一個能顯示中文的字型,而這次我所使用的是 SNsanafonGyou.ttf,各位也可以自行去找尋喜歡的中文字型。

如果沒有選取一個能顯示中文的字型,出來的 word cloud 就會全變成長方形,如下圖:

沒有選取字型的錯誤示範
# indicate the font path that can display Chinese
font_path = 'SNsanafonGyou.ttf'

Step 3 - Generate the Word Cloud

準備好一切之後,我們就可以開始做一個獨一無二的 word cloud 了!

from wordcloud import WordCloud
import matplotlib.pyplot as plt
wc = WordCloud(font_path=font_path, background_color="black", max_words=2000, mask=mask, max_font_size=300, random_state=1)
wc.generate_from_text(text)
wc.recolor(color_func=color_func, random_state=2)
# save as png
output_path = 'wordcloud.png'
wc.to_file(output_path)
# display the word cloud
plt.rcParams["figure.figsize"] = (25,25)
plt.imshow(wc)
plt.axis("off")
plt.show()
三種不同顏色選擇的 word cloud (左: plain color, 中: image color, 右: palettable color set )

Conclusion

這是我第一次打這類型的教學文,用了頗長的時間,希望各位看完以後能掌握到如何做一個合自己心意的中文 word cloud,如果你覺得這篇文章真的能幫到你的話,請你分享給身邊的朋友,讓他們也能學會這種有用的技巧。 未來我們會出一系列的教學文章,歡迎隨追和拍個手支持一下!

另外,如果興趣知道更多這種小技巧或知識,可以瀏覽我的網站:https://cydalytics.blogspot.com/

LinkedIn:

Yeung Wong - https://www.linkedin.com/in/yeungwong/

Carrie Lo - https://www.linkedin.com/in/carrielsc/

Other Articles

  1. Making a Game for Kids to Learn English and Have Fun with Python
  2. Data Visualization Tips (Power BI) — Convert Categorical Variables to Dummy Variables
  3. Data Science Fundamentals (R): Import Data from Excel — readxl
  4. Data Science Fundamentals (R): Import Data from text files — textreadr & readtext
  5. Data Science Fundamentals (R): Import & Export Data in Excel — xlsx
Cyda
Artificial Intelligence
Technology
Innovation
Creativity
Recommended from ReadMedium