【发布时间】:2017-10-19 02:05:46
【问题描述】:
text_file = open("university_towns.txt")
State = {idx: lines.decode('utf-8').strip().replace("[edit]", "")
for idx,lines in enumerate(text_file) if "edit" in lines}
我的代码出现错误:
'ascii' codec can't decode byte 0xe2 in position 6723
我正在使用 Python 3.5。
【问题讨论】:
-
Python 2 还是 Python 3?
-
看起来字节 6723 不是正确的 unicode。将
errors='ignore'传递给`decode()` 可能会有所帮助。 -
在 python 3.x 中,由于您没有指定编码,因此文件以
sys.getdefaultencoding()所说的任何模式打开。lines.decode('utf-8')无效,因为 3.x 字符串没有decode方法,所以你没有走那么远,否则你会有不同的错误。我的猜测是问题出在enumerate(text_file)... 但这意味着您的默认编码是ascii。您可以逐行读取文件,看看是否会出现错误。
标签: python python-3.x utf-8 ascii decode