Python制作詞云的方法
需求:
看到朋友圈有人發(fā)詞云照片,感覺自己也可以玩一玩,于是乎借助wordcloud實現(xiàn)功能。
環(huán)境:
MacOS 10.12 +Python 2.7 +Wordcloud
Windows通用
準(zhǔn)備:
安裝wordcloud
$ pip install wordcloud
SIP功能是Apple在OSX上推出的系統(tǒng)完整性保護功能,新版本的macOS直接用pip安裝報錯,在不關(guān)閉SIP功能的前提下,可以使用
$ pip install wordcloud --user -U
某些情況還會提示錯誤,需要安裝VS for Python,直接上官網(wǎng)下載安裝即可。
實現(xiàn):
源碼
#! /usr/bin/env python
# import
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
# current path
d = path.dirname(__file__)
# Read the whole text.
text = open(path.join(d, 'test.txt')).read()
# read the mask image
test_mask = np.array(Image.open(path.join(d, "test_mask.png")))
stopwords = set(STOPWORDS)
stopwords.add("said")
# setting
wc = WordCloud(background_color="black", max_words=2000, mask=test_mask,
stopwords=stopwords)
# generate word cloud
wc.generate(text)
# plot and show
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.figure()
plt.imshow(test_mask, cmap=plt.cm.gray, interpolation='bilinear')
plt.axis("off")
plt.show()
# store to file
wc.to_file(path.join(d, "test.png"))
輔助文件
test_mask.png

test.txt
The list of big's prior run-ins with the far-right fringe is long and varied. He tweeted fake crime statistics spread by racists to paint black cans as violent, then defended them as credible. He sparked a firestorm last year when he declined to renounce
效果圖

其它說明:
1.文檔可以是任意英文txt文件,以上的是網(wǎng)絡(luò)上英文新聞中的一小段,僅起示例作用。
2.關(guān)于中文支持,有多種方法,主要就是分詞的問題,這里不討論了。
3.我不清楚許多人說的定制是什么意思,因為如果想要自己任意想要的形狀的話,我覺得用PS做一個png圖可以達到同樣的效果,經(jīng)測試也沒有發(fā)現(xiàn)問題。
4.寫的第一篇文章,不足之處歡迎來噴,畢竟我是要學(xué)習(xí)的。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
用python生成mysql數(shù)據(jù)庫結(jié)構(gòu)文檔
大家好,本篇文章主要講的是用python生成mysql數(shù)據(jù)庫結(jié)構(gòu)文檔,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01
Python入門教程(三十八)Python的NumPy庫簡介
這篇文章主要介紹了Python入門教程(三十八)Python的NumPy庫簡介,NumPy 是用于處理數(shù)組的 python 庫,它還擁有在線性代數(shù)、傅立葉變換和矩陣領(lǐng)域中工作的函數(shù),需要的朋友可以參考下2023-05-05
Python二進制數(shù)據(jù)結(jié)構(gòu)Struct的具體使用
在C/C++語言中,struct被稱為結(jié)構(gòu)體。而在Python中,struct是一個專門的庫,用于處理字節(jié)串與原生Python數(shù)據(jù)結(jié)構(gòu)類型之間的轉(zhuǎn)換。本文就詳細(xì)介紹struct的使用方式2021-06-06
python?matplotlib畫圖時坐標(biāo)軸重疊顯示不全和圖片保存時不完整的問題解決
最近工作中遇到了matplotlib保存圖片坐標(biāo)軸不完整的問題,所以這篇文章主要給大家介紹了關(guān)于python?matplotlib畫圖時坐標(biāo)軸重疊顯示不全和圖片保存時不完整問題的解決方法,需要的朋友可以參考下2022-07-07
python和websocket構(gòu)建實時日志跟蹤器的步驟
這篇文章主要介紹了python和websocket構(gòu)建實時日志跟蹤器的步驟,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04

