我正在解析一个来自在线源的XML文件,但是在读取utf-8字符时遇到了问题。现在我已经通读了其他一些处理类似问题的问题,但是到目前为止,没有一个解决方案有效。当前代码如下所示。在
class XMLParser(webapp2.RequestHandler):
def get(self):
url = fetch('some.xml.online')
xml = parseString(url.content)
vouchers = xml.getElementsByTagName("VoucherCode")
for voucher in vouchers:
if voucher.getElementsByTagName("ActivePartnership")[0].firstChild.data == "true":
coupon = Coupon()
coupon.description = str(voucher.getElementsByTagName("Description")[0].firstChild.data.decode('utf-8'))
coupon.prov_key = str(voucher.getElementsByTagName("Id")[0].firstChild.data)
coupon.put()
self.redirect('/admin/coupon')
我由此得到的错误如下所示。它是由description字段中的一个“ü”引起的,我以后在使用数据时也需要显示它。在
File "C:\Users\Vincent\Documents\www\Sparkompass\Website\main.py", line 217, in get coupon.description = str(voucher.getElementsByTagName("Description")[0].firstChild.data.decode('utf-8')) File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 16: ordinal not in range(128)
如果我把描述去掉,一切都会正常运转。在数据库模型定义中,我定义了如下描述:
^{pr2}$尝试2
我也试过这样做:
coupon.description = str(voucher.getElementsByTagName("Description")[0].firstChild.data).decode('utf-8')
这也给了我:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 16: ordinal not in range(128)
任何帮助都将不胜感激!在
更新
XML文件包含德语,这意味着其中更多的字符是UTF-8字符。因此,理想情况下,我现在认为在更高的层次上进行解码可能更好,例如
xml = parseString(url.content)
但到目前为止,我也没能做到。目的是获取ascii字符,因为这是GAE在数据库模型中将其注册为字符串所需的。在
UnicodeEncodeError
^{pr2}$'\xc3\xbc'
u'\xfc'
UnicodeEncodeError
'\xc3\xbc'
你需要什么编码?在
您还可以使用:
这将把所有非拉丁1字符替换为xml实体。在
我通过将描述改为TextProperty来解决这个问题,它没有给出任何错误。我知道,当我这样做的时候,我将不能排序或过滤,但对于描述,这应该是可以的。在
背景信息:https://developers.google.com/appengine/docs/python/datastore/typesandpropertyclasses#TextProperty
相关问题 更多 >
编程相关推荐