熱詞圖很酷炫,也非常適合熱點事件,抓住重點,以圖文結合的方式表現出來,很有沖擊力。下面這段代碼是制作熱詞圖的,用到了以下技術:
jieba,把文本分詞
wordcloud,制作熱圖
chardet,辨別文件的編碼格式,其中中文統一為GB18030,更加的兼容
imageio,提取圖片的形狀
其他:自動識別文件編碼,自動識別txt文件,圖片文件名與txt文件一致,使用的是四大名著的文本(自行百度),部分中國地圖
上代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import os import jieba import wordcloud import chardet import imageio directory = "D:\\" mask = imageio.imread(r "D:\map.jpg" ) # 用于最后圖像圖形 directory_lists = os.scandir(directory) for directory_list in directory_lists: if directory_list.is_dir() or directory_list.path.split( '.' )[ - 1 ] ! = "txt" : continue with open (directory_list.path, 'rb' ) as fd: coding = chardet.detect(fd.read()[: 1000 ])[ 'encoding' ] if coding.upper() = = 'GB2312' or coding = = 'GBK' : coding = 'GB18030' file = open (directory_list.path, 'r' , encoding = coding) text = file .read() file .close() jieba_text = ' ' .join(jieba.lcut(text)) w = wordcloud.WordCloud(height = 800 , width = 1600 , font_path = 'msyh.ttc' , background_color = 'white' , stopwords = { 'Page' }, mask = mask) w.generate(jieba_text) w.to_file( '{}.png' . format (directory_list.path.split( '.' )[ 0 ])) |
輸出:
水滸傳的如下
西游記的如下
仔細看輸出的內容,還是挺有意思的,哈哈哈。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/johnthegreat/p/12595892.html