这是代码:
print '"' + title.decode('utf-8', errors='ignore') + '",' \
' "' + title.decode('utf-8', errors='ignore') + '", ' \
'"' + desc.decode('utf-8', errors='ignore') + '")'
标题和描述由Beautiful Soup 3 (p[0].text 和 p[0].prettify)返回,并且根据BeautifulSoup3文档,它们是UTF-8编码。请注意保留HTML标签。
如果我运行以下命令:
python.exe script.py > out.txt
我遇到了以下错误:
Traceback (most recent call last):
File "script.py", line 70, in <module>
'"' + desc.decode('utf-8', errors='ignore') + '")'
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 264
: ordinal not in range(128)
然而,如果我运行
python.exe script.py
我没有收到任何错误信息。只有当指定输出文件时才会出现此问题。
如何在输出文件中获得良好的UTF-8数据?
decode
超过一次。事实上,你根本不应该调用它。只需设置标准输出的编码并完成即可。这个错误(Python的错误,而不是你的错误)是Python有这种非常烦人的行为,它将重定向的输出与未重定向的输出区别对待。 - tchristerrors='ignore'
,它会隐藏代码中的错误。 - agf