一、生成漢字詞雲圖的代碼如下:
from wordcloud import WordCloud
import matplotlib.pyplot as plt #繪制圖像的模塊
import jieba #jieba分詞
path_txt='E://python/all.txt'
f = open(path_txt,'r',encoding='UTF-8').read()
# 結巴分詞,生成字符串,wordcloud無法直接生成正確的中文詞雲
cut_text = " ".join(jieba.cut(f))
wordcloud = WordCloud(
#設置字體,不然會出現口字亂碼,文字的路徑是電腦的字體一般路徑,可以換成別的
font_path="C:/Windows/Fonts/simfang.ttf",
#設置了背景,寬高
background_color="white",width=1000,height=880).generate(cut_text)
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
說明:
1、其中path_txt的值為生成詞雲文件的所在路徑。
2、字符串界定符前面加字母r或R表示原始字符串,其中的特殊字符不需要進行轉義,但字符串的最后一個字符不能是\符號。
3、通過pip install 安裝所需要的模塊。例如 pip install wordcloud ,pip install jieba, pip install matplotlib。其中在電腦的命令提示符中輸入即可。

4、plt.axis("off")意思是關閉軸線和標簽,與假一樣。
二、生成英文詞雲
1、簡單例子
from wordcloud import WordCloud
import matplotlib.pyplot as plt
f = open('E:/Python/練習/sports.txt','r').read()
wordcloud = WordCloud(background_color = "white" , width = 1000 , height = 860 , margin = 2).generate(f)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
2、設置字體的顏色的例子
from wordcloud import (WordCloud , get_single_color_func)
import matplotlib.pyplot as plt
class SimpleGroupedColorFunc(object):
def __init__(self , color_to_words,default_color):
self.word_to_color = {word:color
for(color , words) in color_to_words.items()
for word in words}
self.default_color = default_color
def __call__(self , word , **kwargs):
return self.word_to_color.get(word , self.default_color)
class GroupedColorFunc(object):
def __init__(self , color_to_words , default_color):
self.color_func_to_words = [
(get_single_color_func(color) , set(words))
for (color , words) in color_to_words.items()]
self.default_color_func = get_single_color_func(default_color)
def get_color_func(self , word):
try:
color_func = next(
color_func for (color_func , words) in self.color_func_to_words
if word in words)
except StopIteration:
color_func = self.default_color_func
return color_func
def __call__(self , word , **kwargs):
return self.get_color_func(word)(word , **kwargs)
f = open('E:/Python/練習/sports.txt','r').read()
wc = WordCloud( width = 1000 , height = 860 , collocations = False ).generate(f)
color_to_words ={
'#00ff00':['important','beat','minute','proud','frist','coach'
],
'red':['Chinese','win','team','said','goal','header'
],
'yellow':['Japan','Korea','South','China'
]
}
default_color = 'grey'
grouped_color_func = GroupedColorFunc(color_to_words , default_color)
wc.recolor(color_func = grouped_color_func)
plt.imshow(wc , interpolation = "bilinear")
plt.axis("off")
plt.show()

python os.path模塊常用方法詳解:https://www.jianshu.com/p/d77ef16a38c3
參考於:https://blog.csdn.net/cskywit/article/details/79285988
