文本生成词云图wordcloud
发布时间丨2021-10-15 13:52:32作者丨zhaomeng浏览丨109
本片文章记录的是帮助农业专业的研究生做一篇关于中国农业政策的毕业发表论文,论文要求对之一是对每个省的农业政策进行词云图的实现,以便直观看出来每篇政策中的出现频率比较高的关键词,以便帮助她进行比较出不同及相同的一些特点。这里记录了使用中文分词对文章进行处理并分词,最后生成词云图。
1.安装 jieba :pip install jieba pip install re
text = """ """ 一串待处理的文本
2.文本预处理
1.使用正则表达式去除文本中的无用字符及特殊符号
import re
import jieba
# wenben
pattern = re.compile(u'[a-zA-Z\u4E00-\u9FA5]')
pattern1 = re.compile(r'[0-9]')
d = pattern.findall(text.encode('utf8').decode('utf8'))
print("".join(d))
2.使用文件保存处理过的纯净文本
with open('fil_text.txt', 'w', encoding='utf8')as f:
f.write("".join(d))
3. 使用结巴分词全模式进行文本处理,保存为一个个以空格分隔的词语
with open('fil_text.txt', 'r', encoding='utf8')as f:
data = f.readlines()
s = jieba.cut(data[0], cut_all=True)
for t in s:
with open('result.txt','a+',encoding='utf8')as g:
g.write(t+' ')
print(t)
4.处理过的文本信息,保存到txt文件
for t in s:
with open('result.txt','a+',encoding='utf8')as g:
g.write(t+' ')
print(t)
3.词云生成,并保存为图片
f = open('./result.txt', 'r',encoding='utf8').read() # 生成词云的文档
wordcloud = WordCloud(
background_color='white', # 背景颜色,根据图片背景设置,默认为黑色
# mask = backgroup_Image, #笼罩图
font_path='./msyh.ttc', # 若有中文需要设置才会显示中文
width=1000,
height=860,
max_words=100,
margin=2).generate(f) # generate 可以对全部文本进行自动分词
# 参数 width,height,margin分别对应宽度像素,长度像素,边缘空白处
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
# 保存图片:默认为此代码保存的路径
wordcloud.to_file('touxiang.jpg')
4.完成文本的 词语生成!