我已经用特殊字符(捷克字母)解析了一些docx文件(UTF-8编码的XML)。当我试图输出到stdout时,一切都很顺利,但我无法将数据输出到文件
Traceback (most recent call last):
File "./test.py", line 360, in
ofile.write(u'\t\t\t\t\t\n')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 37: ordinal not in range(128)
尽管我显式地将word
变量强制转换为unicode类型(type(word)
返回unicode),但我试图用.encode('utf-8)
对其进行编码,但仍然遇到此错误。
下面是代码的示例:
for word in word_list:
word = unicode(word)
#...
ofile.write(u'\t\t\t\t\t<feat att="writtenForm" val="'+word+u'"/>\n')
#...
我还尝试了以下方法:
for word in word_list:
word = word.encode('utf-8')
#...
ofile.write(u'\t\t\t\t\t<feat att="writtenForm" val="'+word+u'"/>\n')
#...
甚至这两者的结合:
word = unicode(word)
word = word.encode('utf-8')
我有点绝望,所以我甚至尝试在ofile.write()
中编码单词变量
ofile.write(u'\t\t\t\t\t<feat att="writtenForm" val="'+word.encode('utf-8')+u'"/>\n')
我希望你能告诉我我做错了什么。
我在写word文档(.docx)时也遇到过类似的错误。特别是带有欧元符号(欧元)。
导致了错误:
UnicodeDecodeError:“ascii”编解码器无法解码位置0中的字节0xe2:序号不在范围(128)内
我是如何解决这个问题的:
我希望这有帮助!
ofile
是bytestream,您正在向其写入字符串。因此,它试图通过编码到字节字符串来处理您的错误。这通常只对ASCII字符安全。由于word
包含非ASCII字符,因此失败:通过使用^{} 打开文件,使用类似
'wt'
的模式和显式编码,使ofile
成为文本流:或者,您也可以对几乎相同的接口使用^{} ,或者使用^{} 手动编码所有字符串。
菲哈格的回答是正确的。我只想建议使用显式编码手动将unicode转换为字节字符串:
(也许你想知道如何使用基本的机制,而不是像
io.open
这样的高级巫术和黑色魔法。)相关问题 更多 >
编程相关推荐