用python實現詞云效果實例介紹
更新時間:2022年01月18日 08:52:12 作者:autofelix
大家好,本篇文章主要講的是用python實現詞云效果實例介紹,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下
什么是詞云
詞云其實就是就是對網絡文本中出現頻率較高的〝關鍵詞〞予以視覺上的突出,形成〝關鍵詞云層〞或〝關鍵詞渲染〞從而過濾掉大量的文本信息
詞云也是數據可視化的一種形式。給出一段文本,根據關鍵詞的出現頻率而生成的一幅圖像,人們只要掃一眼就能夠明白其文章主旨。
一、特效預覽

詞云圖
二、程序原理
從給出的文本中,進行分詞處理,然后將每個詞出現的的頻率進行統(tǒng)計從給出的背景圖片上,讀出圖片信息將文本按照出現的頻率進行畫圖,出現頻率越高,字體設置越大

你聽懂了嗎
三、程序源碼
jieba模塊:用來進行分詞處理PIL模塊:用來進行圖片處理wordcloud模塊:用來進行生成詞云
#!/usr/bin/env python
# encoding: utf-8
import jieba
import numpy as np
import PIL.Image as Image
from wordcloud import WordCloud
class wordCloud:
'''
This is a main Class, the file contains all documents.
One document contains paragraphs that have several sentences
It loads the original file and converts the original file to new content
Then the new content will be saved by this class
'''
def __init__(self):
self.bg_img = 'assets/picture.jpeg'
self.word_path = 'assets/word.txt'
def hello(self):
'''
This is a welcome speech
:return: self
'''
print('*' * 50)
print(' ' * 20 + '詞云制作')
print(' ' * 5 + 'Author: autofelix Date: 2022-01-17 13:14')
print('*' * 50)
return self
def run(self):
'''
The program entry
'''
with open(self.word_path, 'r') as f:
word = f.read()
cut_word = ' '.join(jieba.cut(word))
color_mask = np.array(Image.open(self.bg_img))
word_cloud = WordCloud(
# 設置字體,不指定就會出現亂碼
font_path='/System/Library/Fonts/PingFang.ttc',
# 設置背景色
background_color='white',
# 詞云形狀
mask=color_mask,
# 允許最大詞匯
max_words=120,
# 最大號字體
max_font_size=2000
).generate(cut_word)
word_cloud.to_file('word_cloud.jpg')
im = word_cloud.to_image()
im.show()
if __name__ == '__main__':
wordCloud().hello().run()總結
到此這篇關于用python實現詞云效果實例介紹的文章就介紹到這了,更多相關python詞云內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

