Python的UnicodeDecodeError

在使用Python进行文本分析的时候,遇到了UnicodeDecodeError类型的错误。

1. 提取童话Alice in Wonderland的文本,并尝试计算它包含多少个单词
# 分析文本
filename = 'D:\\Python_work\\10_文件和异常\\alice.txt'

try:
    with open(filename, 'r') as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    print("Sorry, the file " + filename + " does not exist.")
else:
    words = contents.split()
    num_words = len(words)
    print("The file " + filename + "has about " + str(num_words) + " words.")
2. 此时运行结果却报错了:
C:\Users\Tracy\AppData\Local\Programs\Python\Python36\python.exe D:/Python_work/10_文件和异常/10.3异常.py
Traceback (most recent call last):
  File "D:/Python_work/10_文件和异常/10.3异常.py", line 52, in <module>
    contents = f_obj.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0x99 in position 1011: illegal multibyte sequence

Process finished with exit code 1

仔细查看报错类型,应该是文本的编码格式有问题。
用记事本打开alice.txt,发现此文件的编码格式为UTF-8,将其修改为ANSI后保存。
在这里插入图片描述

3. 修改完毕已经能够正常运行了
C:\Users\Tracy\AppData\Local\Programs\Python\Python36\python.exe D:/Python_work/10_文件和异常/10.3异常.py
The file D:\Python_work\10_文件和异常\alice.txthas about 29465 words.

Process finished with exit code 0
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值