繁体   English   中英

Python中的编码问题-使用UTF-8时,“ ascii”编解码器无法编码字符“ \\ xe3”

[英]Encoding problems in Python - 'ascii' codec can't encode character '\xe3' when using UTF-8

我创建了一个程序来打印一些html内容。 我的源文件在utf-8中,服务器的终端在utf-8中,并且我还使用了:

out = out.encode('utf8')

确保字符链在utf8中。 尽管如此,当我在字符串中使用诸如“ã”,“é”之类的字符时,我得到:

UnicodeEncodeError: 'ascii' codec can't encode character '\xe3' in position 84: ordinal not in range(128)

在我看来,打印后:

print("Content-Type: text/html; charset=utf-8 \n\n")

它被迫使用ASCII编码...但是,我只是不知道会是这种情况。

我猜您应该将文件作为unicode对象读取,这样就可能不需要对其进行编码。

import codecs
file = codecs.open('file.html', 'w', 'utf-8')

非常感谢。

这说明了我如何使用Python 3.4.1解决编码问题:首先,我在代码中插入了以下行以检查输出编码:

print(sys.stdout.encoding)

我看到了输出编码为:

ANSI_X3.4-1968 -

代表ASCII,不支持'ã','é'等字符。

因此,我删除了上一行,并在此处插入了这些代码,以更改这些代码行的标准输出编码

import codecs

if sys.stdout.encoding != 'UTF-8':
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
if sys.stderr.encoding != 'UTF-8':
    sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')

这是我找到信息的地方:

http://www.macfreek.nl/memory/Encoding_of_Python_stdout

PS:每个人都说更改默认编码不是一个好习惯。 我真的不知道 就我而言,它对我来说很好用,但是我正在构建一个非常小而简单的Web应用程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM