我正在尝试读取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')