gpt4 book ai didi

python - 为什么打印到 utf-8 文件会失败?

转载 作者:行者123 更新时间:2023-11-28 23:05:10 25 4
gpt4 key购买 nike

所以我今天下午遇到了一个问题,我能够解决它,但我不太明白为什么它有效。

这与我上周遇到的问题有关:python check if utf-8 string is uppercase

基本上,以下将不起作用:

#!/usr/bin/python

import codecs
from lxml import etree

outFile = codecs.open('test.xml', 'w', 'utf-8') #cannot use codecs.open()

root = etree.Element('root')
sect = etree.SubElement(root,'sect')


words = ( u'\u041c\u041e\u0421\u041a\u0412\u0410', # capital of Russia, all uppercase
u'R\xc9SUM\xc9', # RESUME with accents
u'R\xe9sum\xe9', # Resume with accents
u'R\xe9SUM\xe9', ) # ReSUMe with accents

for word in words:
print word
if word.encode('utf8').decode('utf8').isupper(): #.isupper won't function on utf8
title = etree.SubElement(sect,'title')
title.text = word
else:
item = etree.SubElement(sect,'item')
item.text = word

print>>outFile,etree.tostring(root,pretty_print=True,xml_declaration=True,encoding='utf-8')

它失败了:

Traceback (most recent call last):
File "./temp.py", line 25, in
print >>outFile,etree.tostring(root,pretty_print=True,xml_declaration=True,encoding='utf-8')
File "/usr/lib/python2.7/codecs.py",
line 691, in write
return self.writer.write(data) File "/usr/lib/python2.7/codecs.py",
line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec
can't decode byte 0xd0 in position 66:
ordinal not in range(128)

但是如果我打开没有 codecs.open('test.xml', 'w', 'utf-8') 的新文件,而是使用outFile = open('test.xml', 'w') 它运行良好。

那么发生了什么??

  • 由于 etree.tostring() 中指定了 encoding='utf-8' 是否再次对文件进行编码?

  • 如果我离开 codecs.open() 并删除 encoding='utf-8' 文件就会变成一个 ascii 文件。为什么?因为我认为 etree.tostring() 有一个默认的 ascii 编码?

  • 但是 etree.tostring() 只是被写入标准输出,然后被重定向到创建为 utf-8 文件的文件?

    • print>> 是否没有像我预期的那样工作? outFile.write(etree.tostring()) 的行为方式相同。

基本上,为什么这行不通?这里发生了什么。这可能是微不足道的,但我显然有点困惑,并且想弄清楚为什么我的解决方案有效,

最佳答案

您已使用 UTF-8 编码打开文件,这意味着它需要 Unicode 字符串。

tostring 正在编码为 UTF-8(以字节串的形式,str),您正在将其写入文件。

因为文件需要 Unicode,所以它使用默认的 ASCII 编码将字节串解码为 Unicode,然后它可以将 Unicode 编码为 UTF-8。

不幸的是,字节串不是 ASCII。

编辑:避免此类问题的最佳建议是在内部使用 Unicode,对输入进行解码,对输出进行编码。

关于python - 为什么打印到 utf-8 文件会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6527420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com