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

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['KaiTi']
with open(r'E:\pythoncoda\read\notebook.txt', encoding='utf-8') as file:
    # contents = file.read()
    # print(contents)
    #  逐行输出,需要把上面两行注释掉,否则不能输出
    # for line in file:
    #     print('line:', line)
    # 第二种成行输出方法
    contents = file.readlines()
    print(contents)
newList = []
for content in contents:
    newContent = content.replace('\n', '')
    money = newContent.split(':')[-1]
    newList.append(int(money))
print(newList)
x = [1, 2, 3, 4, 5, 6]
y = newList
plot = plt.plot(x, y, 'r', label='销售')
plt.xlabel('month')
plt.ylabel('money')
plt.savefig('销售额.png')
plt.legend()
plt.show()

# 求平均值
sum0 = 0
for money in newList:
    sum0 += money
average = sum0 / len(newList)
print("average:", average)

average2 = sum(newList)/len(newList)
print("average2:", average2)
import matplotlib.pyplot as plt
with open(r'E:\pythoncoda\read\notebook.txt') as file:

对txt文件进行读取,出现错误提示 ‘UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 2: illegal multibyte sequence’

解决方法:在读取文件代码处加上 ;encoding='utf-8'

再次运行就不会报错。

画图时遇到 “No handles with labels found to put in legend.”报错,翻译过来为没有找到标签的手柄,可以放在图例中。

在plot函数里加上,label=‘销售’。即可解决报错。

出现‘RuntimeWarning: Glyph 21806 missing from current font. font.set_text(s, 0, flags=flags)’
是因为没有设置字体,所以图例没有显示出来。

 在开始代码模块加入‘matplotlib.rcParams['font.sans-serif'] = ['KaiTi']’即可解决。

来源:A_beard

物联沃分享整理
物联沃-IOTWORD物联网 » ‘UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0x80 in position 2: illegal multibyte sequence’

发表评论