用Python进行文本分析时出现UnicodeDecodeError错误的解决方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28616789/article/details/79261176

问题:利用Python对文本进行分析时,出现UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xef in position 0: ordinal not in range(128)

先看下面这段Python代码:

filename = 'alice.txt'
try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)
else:
    # 计算文件大致包含多少单词
    words = contents.split()
    num_words = len(words)
    print("The file " + filename + " has about " + str(num_words) + " words.")

运行的结果如下:

  File "/Users/tiramisu/python_work/10/alice.py", line 5, in <module>
    contents = f_obj.read()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)

正是出现了标题中所说的UnicodeDecodeError。

这个问题我在网上找了很多方法,都没能成功解决。最后经过一番波折,终于成功解决了这个问题。

方法就是:

在打开文本的时候,就用utf-8格式。

就我这个代码而言,只需将第3行的

with open(filename) as f_obj:

修改为:

with open(filename, encoding='utf-8') as f_obj:

即可。

修改后再次运行改代码,结果如下:
这里写图片描述

至此,该问题已经解决。

猜你喜欢

转载自blog.csdn.net/qq_28616789/article/details/79261176