python 报错"UnicodeDecodeError: 'utf-8' codec can't decode byte"的解决办法

最近写了一个Python小程序,用来统计《三国演义》中人物出场次数的。从网上下载一个”三国演义.txt”的文件,但是后来程序运行时出现以下报错: 
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xa1 in position 0: invalid start byte 
后来经过不断查找终于找到了解决办法。

由于我在程序中设定文件打开的编码格式为“utf-8”,但是我后来用电脑的记事本打开这个”三国演义.txt”文件,然后在点击另存为的时候,发现原文件的编码方式是“ANSI”. 哦哦哦哦哦哦哦哦哦哦哦。。。。不报错才怪呢!

解决办法很简单,只需要在另存为的时候,选择编码方式为:UTF-8即可,就像下面这样 

运行代码

import jieba

txt=open("threeKindoms.txt",'r',encoding='utf-8').read()
words=jieba.lcut(txt)
counts={}

for word in words:
    if len(word)==1:
        continue
    else:
        counts[word]=counts.get(word,0)+1
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(15):
    word,count=items[i]
    print("{0:<10}{1:>5}".format(word,count))

运行结果:

猜你喜欢

转载自blog.csdn.net/weixin_42686879/article/details/89495413