Python Unicode编码错误序号不在范围内< 128>与欧元符号

时间:2013-03-06 02:06:54

标签: python unicode python-2.7 ascii

我必须在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,对吗?),但我认为正在做#coding:utf-8会解决这个问题。我也尝试添加.encode(utf-8),以便名称看起来像

name = nameObj.childNodes[0].nodeValue.encode(utf-8)

但这也不起作用。我究竟做错了什么? (如果有人想知道,我正在使用Python 2.7.3)

编辑:Python在fout.write()行崩溃了 - 在名称字段如下的地方它会很好:

<name>United States, USD</name>

但是会在名称字段上废弃,例如:

<name>France, € </name>

2 个答案:

答案 0 :(得分:21)

当您使用open内置函数在python中打开文件时,您将始终在ascii中读取该文件。要使用其他编码访问它,您必须使用编解码器:

import codecs
fout = codecs.open('data.txt','w','utf-8')

答案 1 :(得分:5)

看起来你正在从XML解析器中获取Unicode数据,但是在编写它之前你没有对它进行编码。您可以在将结果写入文件之前对结果进行显式编码:

text = ",".join(stuff) # this will be unicode if any value in stuff is unicode
encoded = text.encode("utf-8") # or use whatever encoding you prefer
fout.write(encoded)