Python 中的编码问题 - 'ascii' 编解码器在使用 UTF-8 时无法对字符 '\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
P.S.: 每个人都说更改默认编码不是一个好习惯。我真的不知道。就我而言,它对我来说效果很好,但我正在构建一个非常小而简单的网络应用程序。
我创建了一个程序来打印一些 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
P.S.: 每个人都说更改默认编码不是一个好习惯。我真的不知道。就我而言,它对我来说效果很好,但我正在构建一个非常小而简单的网络应用程序。