基于python生成詞云圖的代碼示例
類似生成各種形狀的云圖,我也會啦!
其實也就是針對新手吧,我估計老手分分鐘,哈哈哈,我怕我忘了,隨手記錄下~
四個步驟吧:
- 讀文件
- 分詞
- 生成詞云圖
- 顯示詞云圖
1. 讀文件
使用了下 codecs 庫,讀取內(nèi)容更方便。
import codecs def get_file_content(filePath): with codecs.open(filePath, 'r', 'utf-8') as f: txt = f.read() return txt
2. 分詞
jieba
是一個分詞庫,可以將一段文本分割成詞語。cut 是將文本精確切分開,不存在冗余詞語。比如顏醬是一個厲害的廚師,會變成['顏醬', '厲害', '廚師']
。 Counter
是一個計數(shù)器,可以統(tǒng)計詞語出現(xiàn)的次數(shù),most_common 是取出最常用的詞語。
import jieba from collections import Counter def get_words(txt): # 先分詞,得到詞語數(shù)組 seg_list = jieba.cut(txt) # 開始計數(shù) c = Counter() for x in seg_list: if len(x)>1 and x != '\r\n': c[x] += 1 word_list = [] print('常用詞頻度統(tǒng)計結(jié)果') # 統(tǒng)計前99個詞 for (k,v) in c.most_common(99): word_list.append(str(k)) # 將詞語生成文本文件 file = open("./dist/out_words.txt", 'w').close() with open("./dist/out_words.txt",'a+',encoding='utf-8') as writeFile: for (k,v) in c.most_common(99): # 統(tǒng)計前99個詞 writeFile.write(str(k)) writeFile.write(str(v)) writeFile.write('\n') print(word_list) # ['發(fā)展','平安'] return word_list
3. 生成云圖
wordcloud 是一個詞云庫,可以將詞語生成詞云圖片。
import wordcloud; def generate_cloud_image(file_path, shape_image_path): word_list = get_words(get_file_content(file_path)) string = ' '.join(word_list) # 讀取詞云形狀圖片 image = imageio.v2.imread(shape_image_path) # 先實例化一個詞云對象 wc = wordcloud.WordCloud(width=image.shape[0], # 詞云圖寬度同原圖片寬度 height=image.shape[1], background_color='white', # 背景顏色白色 font_path='Arial Unicode.ttf', # 指定字體路徑,微軟雅黑,可從自帶的字體庫中找 mask=image, # mask 指定詞云形狀圖片,默認為矩形 scale=3) # 默認為1,越大越清晰 # 生成詞云 wc.generate(string) # 保存成文件,output_wordcloud.png,詞云圖 wc.to_file('dist/output_wordcloud.png') # 彈出圖片顯示 alert_image('dist/output_wordcloud.png')
4. 顯示詞云圖
matplotlib
是一個繪圖庫,可以將圖片顯示出來,plt 用于顯示圖片,mpimg 用于讀取圖片。
# # plt用于顯示圖片 import matplotlib.pyplot as plt # mpimg 用于讀取圖片 import matplotlib.image as mpimg def alert_image(image_path): # 這里是讓詞云圖彈出來顯示 lena = mpimg.imread(image_path) # 讀取和代碼處于同一目錄下的 lena.png # 此時 lena 就已經(jīng)是一個 np.array 了,可以對它進行任意處理 lena.shape #(512, 512, 3) plt.imshow(lena) # 顯示圖片 plt.axis('off') # 不顯示坐標軸 plt.show()
這就可以了!
其他文件
準備好文件實驗:
input.txt
cloud.jpg
generate_cloud_image.py
generate_cloud_image.py:
import codecs import jieba import imageio import wordcloud import matplotlib.pyplot as plt import matplotlib.image as mpimg from collections import Counter # def get_words(txt):... # def get_file_content:... # def alert_image(image_path):... # def generate_cloud_image(file_path, shape_image_path):... generate_cloud_image('input.txt', 'cloud.jpg')
完整版:
import codecs import jieba import imageio import wordcloud import matplotlib.pyplot as plt import matplotlib.image as mpimg from collections import Counter # get_words函數(shù)用于統(tǒng)計詞頻,生成out.txt,展示詞語和詞頻 如發(fā)展218 堅持170 def get_words(txt): seg_list = jieba.cut(txt) c = Counter() for x in seg_list: if len(x)>1 and x != '\r\n': c[x] += 1 word_list = [] print('常用詞頻度統(tǒng)計結(jié)果') # 統(tǒng)計前99個詞 for (k,v) in c.most_common(99): word_list.append(str(k)) file = open("./out_words.txt", 'w').close() with open("./out_words.txt",'a+',encoding='utf-8') as writeFile: for (k,v) in c.most_common(99): # 統(tǒng)計前99個詞 writeFile.write(str(k)) writeFile.write(str(v)) writeFile.write('\n') print(word_list) # ['發(fā)展','平安'] return word_list def get_file_content(filePath): with codecs.open(filePath, 'r', 'utf-8') as f: txt = f.read() return txt def alert_image(image_path): # 這里是讓詞云圖彈出來顯示 lena = mpimg.imread(image_path) # 讀取和代碼處于同一目錄下的 lena.png # 此時 lena 就已經(jīng)是一個 np.array 了,可以對它進行任意處理 lena.shape #(512, 512, 3) plt.imshow(lena) # 顯示圖片 plt.axis('off') # 不顯示坐標軸 plt.show() # 根據(jù)文件生成詞云圖,file_path是文本文件路徑,shape_image_path是詞云圖的圖片途徑 def generate_cloud_image(file_path, shape_image_path): word_list = get_words(get_file_content(file_path)) string = ' '.join(word_list) # 讀取詞云形狀圖片 image = imageio.v2.imread(shape_image_path) # 生成詞云圖片,先實例化一個詞云對象 wc = wordcloud.WordCloud(width=image.shape[0], # 詞云圖寬度同原圖片寬度 height=image.shape[1], background_color='white', # 背景顏色白色 font_path='Arial Unicode.ttf', # 指定字體路徑,微軟雅黑,可從win自帶的字體庫中找 mask=image, # mask 指定詞云形狀圖片,默認為矩形 scale=3) # 默認為1,越大越清晰 # 再給詞云 wc.generate(string) # 保存成文件,output_wordcloud.png,詞云圖 wc.to_file('output_wordcloud.png') alert_image('output_wordcloud.png') generate_cloud_image('input.txt', 'cloud.jpg')
運行
記得先pip3 install jieba imageio wordcloud matplotlib
然后python3 generate_cloud_image.py
??:文件在同一目錄,進到這個目錄下運行命令
以上就是基于python生成詞云圖的代碼示例的詳細內(nèi)容,更多關(guān)于python生成詞云圖的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
pandas基礎?Series與Dataframe與numpy對二進制文件輸入輸出
這篇文章主要介紹了pandas基礎Series與Dataframe與numpy對二進制文件輸入輸出,series是一種一維的數(shù)組型對象,它包含了一個值序列和一個數(shù)據(jù)標簽2022-07-07Python數(shù)據(jù)分析matplotlib折線圖案例處理
這篇文章主要介紹了Python數(shù)據(jù)分析matplotlib折線圖案例處理,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08Flask實現(xiàn)swagger在線文檔與接口測試流程詳解
Flask是一個使用Python編寫的輕量級Web應用框架。其WSGI工具箱采用 Werkzeug,模板引擎則使用Jinja2。Flask使用 BSD 授權(quán)。Flask也被稱為“microframework”,因為它使用簡單的核心,用 extension 增加其他功能,本篇帶你用Flask實現(xiàn)swagger在線文檔與接口測試2022-07-07python網(wǎng)絡編程學習筆記(二):socket建立網(wǎng)絡客戶端
看了這一節(jié),突然之間對python網(wǎng)絡編程學習筆記(1)中的一些不理解的問題有了認識,至少明白了socket是怎么回事。這里關(guān)于socket的起源等問題就不做筆記記錄了,直接進入主題2014-06-06Python PyTorch實現(xiàn)Timer計時器
這篇文章主要為大家詳細介紹了Python PyTorch如何實現(xiàn)簡單的Timer計時器,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-08-08