Unicode解码错误:'ascii'编解码器无法解码位置 81201 中的字节0xe2:序号不在范围内(128)



我正在尝试读取dictionary_format_file.txt,但我一直在列出错误。

我阅读了其他文章,它们完全有道理,但是我仍然无法解决问题。

任何帮助都将不胜感激。

import ast
path = '/Users/xyz/Desktop/final/'
filename = 'dictionary_format_text_file.txt'
with open((path+filename), 'r') as f:
    s=f.read()
    s=s.encode('ascii', 'ignore').decode('ascii')

错误:

  Traceback (most recent call last):
  File "/Users/xyz/Desktop/final/boolean_query.py", line 347, in <module>
    s=s.encode('ascii', 'ignore').decode('ascii')
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
builtins.UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 81201: ordinal not in range(128)

f.read是返回字节字符串,而不是unicode字符串。当您尝试在其上使用encode时,Python 2尝试使用错误打开的'ascii'编解码器首先解码(Python 3只会在不尝试解码的情况下给您一个错误)。正是隐藏的decode正在生成错误。您可以通过摆脱冗余encode来轻松避免它:

s=s.decode('ascii', 'ignore')

相关内容

最新更新