python作詞雲 (WordCloud)

python作詞雲 (WordCloud)

1. 安裝

某個教程給出的方法,到[這裏][1]下載相應的wordcolud,而後到相應目錄pip安裝。 
 其實直接
pip install wordcloud

就ok了 ,進入python。 import wordcloud成功便可。
html

##2. 文檔簡要說明
enter description here
能夠看到文檔主要就3個主要的函數,目前主要介紹WordCloud模塊以及相關的函數。python

  1. WordCloud()
class wordcloud.WordCloud(font_path=None, width=400, height=200, margin=2, ranks_only=None, prefer_horizontal=0.9, mask=None, scale=1, color_func=None, max_words=200, min_font_size=4, stopwords=None, random_state=None, background_color='black', max_font_size=None, font_step=1, mode='RGB', relative_scaling=0.5, regexp=None, collocations=True, colormap=None, normalize_plurals=True)

font_path:字體位置,中文的時候須要制定一些。
prefer_horizontal:float,水平方向的擬合次數,若是小於1,一旦水平方向不合適就旋轉這個詞。 意思就是詞雲的算法水平詞和豎直方向詞的一種數量衡量。
mask :控制詞雲的背景。nd-array or None (default=None)若是是空,就使用width和height參數。否則使用mask做爲背景。
scale:縮放圖片
max_words:顯示的最大詞
stopwords:停用詞
relative_scaling:這個比較有意思,若是true,字體的大小與詞語順序有關。false,字體大小與詞雲頻率有關。web

  1. 相關函數

fit_words(frequencies) 根據單詞與頻率生成詞雲
generate(tex) 根據文本直接生成詞雲,僅限 英文的
generate_from_frequencies(frequencies, max_font_size=None) 根據單詞與頻率生成詞雲,能夠指定最大數目
generate_from_text()根據文本直接生成詞雲。英文的
process_text(text) 根據text生成單詞的統計數目,返回{word,int},去除了停用詞。只限於英文的算法

關於fit_words的參數問題,
enter description here
讓咱們傳的是一個tuple,包含了word和frequency,實際我這麼作的時候參數是錯誤了,看一下源代碼dom

def fit_words(self, frequencies):
        """Create a word_cloud from words and frequencies. Alias to generate_from_frequencies. Parameters ---------- frequencies : array of tuples A tuple contains the word and its frequency. Returns ------- self """
        return self.generate_from_frequencies(frequencies)

參數說明仍然說是用「 A tuple contains the word and its frequency.」,又去調用了self.generate_from_frequencies(frequencies),ide

def generate_from_frequencies(self, frequencies, max_font_size=None):
        """Create a word_cloud from words and frequencies. Parameters ---------- frequencies : dict from string to float A contains words and associated frequency. max_font_size : int Use this font-size instead of self.max_font_size Returns ------- self """
        # make sure frequencies are sorted and normalized
        frequencies = sorted(frequencies.items(), key=item1, reverse=True)
        frequencies = frequencies[:self.max_words]
        # largest entry will be 1
        max_frequency = float(frequencies[0][4])

        frequencies = [(word, freq / max_frequency)
                       for word, freq in frequencies]

這個時候的參數成了"dict from string to float",並且裏面那個列表生成式 至關於生成了一個新的 frequencies ,這個新的 frequencies 是個array of tuple。因此咱們仍是要傳字典形式的。只不過函數內部變成了 array of tuple 。。。。。年久未修?函數

3. 知乎教育水平 生成詞雲實例

#coding=utf-8


#導入wordcloud模塊和matplotlib模塊
from wordcloud import WordCloud,ImageColorGenerator
import  matplotlib.pyplot as plt
from scipy.misc import imread
import jieba
import jieba.analyse

content = (",").join(data2['教育經歷'].values.tolist())#dataframe格式數據
tags = jieba.analyse.extract_tags(content, topK=200, withWeight=False)

text =" ".join(tags)
print(tags)

#讀入背景圖片
bj_pic=imread('1.png')

#生成詞雲(一般字體路徑均設置在C:\\Windows\\Fonts\\也可自行下載)
font=r'C:\\Windows\\Fonts\\STFANGSO.ttf'#不加這一句顯示口字形亂碼  ""報錯 
wordcloud=WordCloud(mask=bj_pic,background_color='white',font_path=font,scale=0.5).generate_from_text(text)  #直接根據文本生成 詞雲


plt.imshow(wordcloud)
plt.axis('off')
plt.show()

wordcloud.to_file('test2.jpg')

enter description here

能夠試着停用詞,university,或者直接在tags裏把不想要的刪除。圖片很小,用了scale=0.5
enter description here字體

嘗試了一下fit_words,必須傳入字典形式的。!!!this

wordcloud = WordCloud(mask=bj_pic,background_color='white',font_path=font,scale=3.5).fit_words({"sb":3,"我是":4,"操":10})

plt.imshow(wordcloud)
plt.axis('off')
plt.show()
相關文章
相關標籤/搜索