我必须阅读Python中的XML文件并获取各种信息,我遇到了一个令人沮丧的Unicode编码错误,即使使用google也无法发现。
以下是我的代码片段:
#!/usr/bin/python
# coding: utf-8
from xml.dom.minidom import parseString
with open('data.txt','w') as fout:
#do a lot of stuff
nameObj = data.getElementsByTagName('name')[0]
name = nameObj.childNodes[0].nodeValue
#... do more stuff
fout.write(','.join((name,bunch of other stuff))
当我正在解析的一个名称条目包含一个欧元符号时,这个惊人的崩溃。错误如下:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 60: ordinal not in range(128)
我明白为什么欧元区的信号会把事情搞砸(因为现在是128点,对吧?),但我认为编写代码:utf-8可以解决这个问题。我还尝试了添加.encode(utf-8),以便名称看起来像
name = nameObj.childNodes[0].nodeValue.encode(utf-8)
但这也不管用。我做错什么了?(如果有人想知道,我正在使用Python2.7.3)
编辑:Python在fout.write()行崩溃——它将在名称字段如下的地方正常运行:
<name>United States, USD</name>
但是会在名字栏上浪费,比如:
<name>France, € </name>
使用内置函数
open
在python中打开文件时,您将始终以ascii格式读取该文件。要以其他编码方式访问它,必须使用编解码器:看起来您正在从XML解析器中获取Unicode数据,但在将其写出来之前,您没有对其进行编码。在将结果写入文件之前,可以对其进行显式编码:
相关问题 更多 >
编程相关推荐