我正在使用python 2.7.X.我加载了一些XML,XML是utf-8编码的。所以我做了以下几点:
def get_xml(self):
r = requests.get("https://dataserver.com")
xml = r.text
return xml.encode("utf-8")
def parse_xml(xml):
tree = ET.fromstring(xml)
for child in tree:
print " Raw type = " + str(type(child.attrib["name"]))
print "Encoded type = " + str(type(child.attrib["name"].encode("utf-8")))
print child.attrib["name"].encode("utf-8")
print str(child.attrib["name"])
print "------------"
这会导致以下错误:
Raw type = <type 'unicode'>
Encoded type = <type 'str'>
Malmö FF - Paris SG
Traceback (most recent call last):
...
UnicodeEncodeError: 'ascii' codec can't encode characters in position 4-5: ordinal not in range(128)
所以,UnicodeEncodeError
对我来说很清楚。但是,在将unicode
字符串编码为utf-8
字符串后,我希望它能够正确表示。也就是说,Malmö FF
实际应该是Malmö FF
。
我在这里做错了什么?
答案 0 :(得分:0)
我认为你的表达式str(child.attrib["name"])
将使用标准编码对unicode进行编码。你确定这是设置为utf-8吗?我的猜测是你把它设置在latin-1或其他东西上。尝试将其重写为child.attrib["name"].encode("utf-8")
。
答案 1 :(得分:0)
您有很多问题:
您使用的是Windows或使用错误的终端仿真sshing到Unix机箱。您的终端错误地将多字节UTF-8字符转换为两个ISO-8895- *字符:
UTF-8中的Windows-1252 / ISO-8895- * =Malmö
= Malm\xc3\xb6
中的 Malmö
。
如果您使用的是Windows,请不要将UTF-8打印到控制台。使用此:https://github.com/Drekin/win-unicode-console
请勿在打印前进行编码。让Python为你做。如果Python抱怨并且您在Unix上,请确保您的语言环境设置为UTF-8版本,例如: en_US.UTF-8
。如果所有其他方法都失败,请在您的环境中设置PYTHONIOENCODING=UTF-8
除非你真的必须,否则不要将Unicode对象转换为str对象。如果您这样做,请使用.encode("utf-8")
而不是str()
(它们都是str
个对象)以确保使用合适的编码。但是再一次 - 不要这样做。
如果您需要将Unicode对象添加到文件中,请使用:
my_f = io.open("myfile.txt", "w", encoding="utf-8")
my_f.write(my_unicode_object)
将为您编码Unicode对象。