2017-03-01 90 views
-2

我想读取dictionary_format_file.txt,但我不断收到错误信息。UnicodeDecodeError:'ascii'编解码器无法解码位置81201中的字节0xe2:序号不在范围内(128)

我阅读其他帖子,他们是完全有道理的,但我仍然无法解决我的问题。

任何帮助表示赞赏。

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) 
+1

可能重复::“ASCII”编解码器无法编码的字符U“\ XA0”在位置20:可以很容易地通过摆脱冗余encode的避免它序数不在范围内(128) ](http://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20) – DyZ

+0

显然你没有很努力地搜索。 @DYZ和我都在你的帖子的4分钟内找到它。 –

+1

注意:您使用了'with'语句,因此调用'f.close()'是冗余/错误的。 “with”语句的要点在于,它确保在块被退出时资源被释放。 – ShadowRanger

回答

2

f.read返回一个字节的字符串,而不是一个Unicode字符串。当您尝试使用encode时,Python 2会尝试使用编码解码器'ascii'首先对其进行解码,并且错误处于打开状态(Python 3会在未尝试解码的情况下提供错误)。隐藏的decode会产生错误。 [UnicodeEncodeError的

s=s.decode('ascii', 'ignore') 
相关问题