学习使我快乐!!!

UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0x80 in position 2: illegal multibyte sequence

之前写过一个0xad的错误解决,这次是0x80的错误解决。

问题:

最近初步学习了wordcloud库,这是一个关于词云的项目。

代码很简单:

from wordcloud import WordCloud
import matplotlib.pyplot as plt

# 打开文本
file = '../xyj.txt'
text = open(file).read()

# 生成对象
wc = WordCloud(font_path='../Hiragino.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('main2.png')

解决:

根据报错内容,显然是打开文件的时候编译码出了问题,他说gbk的解码方式不行,那就换成utf-8(大小写均可)来解码,为了强制用utf-8,因此需要在代码里说明。

# -*- coding: utf-8 -*-

from wordcloud import WordCloud
import matplotlib.pyplot as plt

# 打开文本
file = '../xyj.txt'
text = open(file,encoding='utf-8').read()

# 生成对象
wc = WordCloud(font_path='../Hiragino.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('main2.png')

能够正常运行了,结果如图:

 

posted @ 2022-04-15 16:47  yyyyyu  阅读(40)  评论(0)    收藏  举报