只要輸入文字,就能立刻產生文字雲。
我們提供 英文版本 與 中文版本,可直接複製貼上就能跑。


需要的套件:
pip install wordcloud jieba matplotlib pillow
⭐ 1. 英文文字雲(最簡單)
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 想要顯示的英文文字
text = "Python is amazing and fun. Machine learning, AI, coding, data science!"
wc = WordCloud(
width=800,
height=400,
background_color="white"
).generate(text)
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
wc.to_file("wordcloud_english.png")
⭐ 2. 中文文字雲(含自動斷詞)
中文一定要分詞,這裡我們使用 jieba:
import os
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import jieba
def find_font():
"""自動尋找系統中文字體"""
possible_fonts = [
# Windows
r"C:\Windows\Fonts\msjh.ttc",
r"C:\Windows\Fonts\msjh.ttf",
r"C:\Windows\Fonts\mingliu.ttc",
r"C:\Windows\Fonts\simhei.ttf",
# Mac
"/System/Library/Fonts/STHeiti Medium.ttc",
"/System/Library/Fonts/PingFang.ttc",
"/Library/Fonts/Arial Unicode.ttf",
# Linux (可能需要安裝:sudo apt install fonts-noto-cjk)
"/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.otf",
]
for font in possible_fonts:
if os.path.exists(font):
print("✔ 使用字體:", font)
return font
raise FileNotFoundError("❌ 找不到適合的中文字體,請安裝 Noto Sans CJK 或確認系統字體。")
#----------------------------------------
# 你的中文文字
#----------------------------------------
text = "今天天氣很好,我想去公園散步,喝咖啡,然後寫 Python 程式。資料分析真的很有趣!"
# 分詞
seg = " ".join(jieba.cut(text))
# 自動找字體
font_path = find_font()
wc = WordCloud(
font_path=font_path,
width=800,
height=400,
background_color="white"
).generate(seg)
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()
wc.to_file("wordcloud_auto_chinese.png")
🎯 使用步驟總結
- 安裝套件:wordcloud、jieba、matplotlib。
- 英文可直接輸入文字。
- 中文需先使用
jieba.cut()分詞。 - 指定中文字體路徑(Windows 多為
msjh.ttf)。 - 使用
wc.to_file()輸出圖片。















