環境:python3.6
第三方庫:matplotlib、wordcloud、PIL
所需材料:一份英文love.txt文件(裏面包含一篇英文文章),一張心形圖片love.jpg
代碼如下:
from wordcloud import WordCloud
import PIL.Image as image
import numpy as np
with open("love.txt") as fp:
text = fp.read()
# print(text)
mask = np.array(image.open("love.jpg"))
wordcloud = WordCloud(
mask=mask
).generate(text)
image_produce = wordcloud.to_image()
image_produce.show()
運行展示效果:
----------------------------分割線-------------------------------------------
以上使用於英文文本,中文文本流程如下
第三方庫:matplotlib、wordcloud、PIL、jieba、numpy
所需材料:一份love.txt文件(裏面包含一篇中文文章),一張心形圖片love.jpg
from wordcloud import WordCloud
import PIL.Image as image
import numpy as np
import jieba
# 分詞
def trans_CN(text):
# 接收分詞的字符串
word_list = jieba.cut(text)
# 分詞後在單獨個體之間加上空格
result = " ".join(word_list)
return result
with open("love.txt",encoding="utf-8") as fp:
text = fp.read()
# print(text)
# 將讀取的中文文檔進行分詞
text = trans_CN(text)
mask = np.array(image.open("love.jpg"))
wordcloud = WordCloud(
# 添加遮罩層
mask=mask,
# 生成中文字的字體,必須要加,不然看不到中文
font_path="C:\Windows\Fonts\STXINGKA.TTF"
).generate(text)
image_produce = wordcloud.to_image()
image_produce.show()
運行效果圖如下: