使用Python建立詞雲
在這個問題中,有一個包含一些文字的檔案。我們必須從這些文字和一個遮罩影像中建立詞雲。程式將詞雲圖像儲存為png格式。
為了實現這個問題,我們需要使用一些Python庫。這些庫是matplotlib、wordcloud、numpy、tkinter和PIL。
要安裝這些庫,我們需要遵循以下命令:
安裝庫
$ sudo pip3 install matplotlib $ sudo pip3 install wordcloud $ sudo apt-get install python3-tk
新增這些庫後,我們可以編寫Python程式碼來執行任務。
演算法
Step 1: Read the data from the file and store it into ‘dataset’. Step 2: Create pixel array from the mask image. Step 3: Create the word cloud from the dataset. Set the background color, mask, and stop-words. Step 4: Store the final image into the disk.
輸入:sampleWords.txt檔案
Python是一種高階的、解釋型的、互動式的和麵向物件的指令碼語言。Python的設計目的是使其高度易讀。它經常使用英語關鍵詞,而其他語言使用標點符號,並且它比其他語言具有更少的語法結構。
Python由Guido van Rossum於20世紀80年代末和90年代初在荷蘭國家數學和計算機科學研究所開發。
Python源於許多其他語言,包括ABC、Modula-3、C、C++、Algol-68、SmallTalk和Unix shell以及其他指令碼語言。
Python受版權保護。與Perl一樣,Python原始碼現在可在GNU通用公共許可證(GPL)下獲得。
Python現在由研究所的核心開發團隊維護,儘管Guido van Rossum仍然在指導其發展方面發揮著至關重要的作用。
另一個輸入是遮罩影像(cloud.png)。最終結果在右側。

示例程式碼
import matplotlib.pyplot as pPlot from wordcloud import WordCloud, STOPWORDS import numpy as npy from PIL import Image dataset = open("sampleWords.txt", "r").read() defcreate_word_cloud(string): maskArray = npy.array(Image.open("cloud.png")) cloud = WordCloud(background_color = "white", max_words = 200, mask = maskArray, stopwords = set(STOPWORDS)) cloud.generate(string) cloud.to_file("wordCloud.png") dataset = dataset.lower() create_word_cloud(dataset)
輸出

廣告