1 数据集格式
【已上传至资源:wordcloud.zip】
山西新闻网
陕西法院网
潇湘法制现场
最高法网站
中国新闻网
深圳晚报
法治日报
人民法治
陕西法院网
文汇报
江苏法制报
云南法制报
新浪内蒙古
潇湘晨报
吉林大酱缸
江西省政府网站
人民网
法制网
潇湘晨报
......
2 所用到的库
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
3 读取TXT文件
def readtxt_list_all_strip(path):
lines = []
with codecs.open(path,'r','utf-8') as r:
for line in r.readlines():
line = line.strip('\n').strip("\r")
lines.append(line)
return lines
4 主函数
if __name__ == '__main__':
path = "media.txt"
word_cloud(path)
5 构建词云
- 数据处理:按行读取TXT文件形成列表
sep_list
(已上传至我的资源)
def word_cloud(path):
sep_list = readtxt_list_all_strip(path)
sep_list = " ".join(sep_list)
print(sep_list)
- 模板图片:决定最后词云的形状
mask = np.array(Image.open('bg.jpg'))
- 字体设置(已上传至我的资源)
font = 'SimHei.ttf'
- 制作词云并保存
wc = WordCloud(
font_path=font,
margin=2,
mask=mask,
background_color='white',
max_font_size=200,
max_words=200,
scale=5,
collocations=False
)
wc.generate(sep_list)
wc.to_file('wordcloud.jpg')
- 图片展示
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
6 词云展示