尝试将Django模型转换为XML时出现UnicodeEncodeError
问题描述:
我找到了一个Python程序:Export Django database to xml file,它将django模型转换为xml表示形式。试图运行程序时出现这些错误。我的模型包含一些用法语写的文字。尝试将Django模型转换为XML时出现UnicodeEncodeError
Traceback (most recent call last):
File "xml_export.py", line 71, in <module>
writer.content(value)
File "xml_export.py", line 41, in content
self.output += str(text)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3:
ordinal not in range(128)
答
它看起来像你的变量text
包含一个非ASCII字符串。
参见:
>>> mystring = u"élève"
>>> mystring
u'\xe9l\xe8ve'
>>> str(mystring)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128)
所以,你首先需要您的串编码为UTF-8
:
>>> str(mystring.encode("utf-8"))
'\xc3\xa9l\xc3\xa8ve'
或者,如果(如注释显示)text
可能包含其他变量类型,除了字符串,使用
self.output += unicode(mystring).encode("utf-8")
答
您是否尝试过使用内置命令:
./manage.py dumpdata --format xml
你u'élève'
使用统一的方式是确定的,所以这应该工作(normalement ...)。
答
严重的是,不要使用链接的代码。这很糟糕,似乎是由完全没有unicode知识,字符编码或甚至如何构建XML文档的人编写的。字符串联合?真?
只是不要使用它。
如果我这样做,我得到:回溯(最后最近一次调用): 文件 “xml_export.py”,71行,在 writer.content(值) 文件 “xml_export.py” 41行,在内容 self.output + = str(text.encode(“utf-8”)) AttributeError:'int'object has no attribute'encode' –
Seitaridis
2011-01-27 14:06:37
这很奇怪。这意味着`text`包含一个整型变量。这反过来使得很难弄清楚为什么在`text`中会出现'é`,除非该变量沿着路径改变其类型(这在Python中是合法的),但是这使得这种情况更加困难。您需要提供更多信息 - “文本”来自哪里?你在做什么? – 2011-01-27 14:09:35