报告词云python"/>
21年政府报告词云python
- 实验内容
1、题目
21年政府报告词云
2、实验代码
- #20203101694 孙成
- from wordcloud import WordCloud, ImageColorGenerator
- from PIL import Image
- import matplotlib.pyplot as plt
- import jieba
- import numpy as np
- def test_chinese_text():
- # 打开文本
- with open('2021政府工作报告.txt', encoding='utf-8') as f:
- text = f.read()
- print(text)
- # 排除不需要的
- counts = {}
- for word in text:
- if len(word) == 1: # 排除单个字符的分词结果
- continue
- else:
- counts[word] = counts.get(word, 0) + 1
- # 生成对象
- wc = WordCloud(font_path='simhei.ttf', width=800, height=600, mode='RGBA', background_color=None).generate(text)
- print(wc)
- # 显示词云
- plt.imshow(wc, interpolation='bilinear')
- plt.axis('off')
- plt.show()
- # 保存到文件
- wc.to_file('wordcloud.png') # 生成图像是透明的
- def test_english_text():
- # 打开文件
- text = open('2021政府工作报告.txt').read()
- # 生成对象
- wc = WordCloud().generate(text=text)
- # 显示词云
- plt.imshow(wc, interpolation='bilinear')
- plt.axis('off')
- plt.show()
- # 保存文件
- wc.to_file('wordcloud.png')
- def test_ch_text_cut():
- # 打开文本
- text = open('2021政府工作报告.txt', encoding='utf-8').read()
- # 中文分词
- print(jieba.cut(text))
- text = ' '.join(jieba.cut(text))
- print(text)
- # 生成对象
- wc = WordCloud(font_path='simhei.ttf', width=800, height=600, mode='RGBA', background_color=None).generate(text)
- # 显示词云
- plt.imshow(wc, interpolation='bilinear')
- plt.axis('off')
- plt.show()
- # 保存到文件
- wc.to_file('wordcloud3.png')
- def test_word_cloud_pic():
- # 打开文本
- text = open('2021政府工作报告.txt', encoding='utf-8').read()
- # 中文分词
- text = ' '.join(jieba.cut(text))
- # 生成对象
- mask = np.array(Image.open("touxiang.JPG"))
- wc = WordCloud(mask=mask, font_path='simhei.ttf', mode='RGBA', background_color=None).generate(text)
- # 从图片中生成颜色
- image_colors = ImageColorGenerator(mask)
- wc.recolor(color_func=image_colors)
- #显示原始图像
- im = Image.open('touxiang.JPG')
- im.show()
- # 显示词云
- plt.imshow(wc, interpolation='bilinear')
- plt.axis("off")
- plt.show()
- # 保存到文件
- wc.to_file('wordcloud5.png')
- if __name__ == '__main__':
- test_chinese_text()
- #test_english_text()
- #test_ch_text_cut()
- #test_word_cloud_pic()
3、运行结果
二、实验报告
请同学们每次实验记得签到,把每次上机的内容保存好,将所有的实验内容压缩为:学号+姓名,统一发给班长,第16到17发送到:346697954@qq邮箱。
更多推荐
21年政府报告词云python
发布评论