我正在解析来自在线资源的 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')
我由此得到的错误显示如下。这是由描述字段中的“ü”引起的,我稍后在使用数据时也需要显示。
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)
如果我去掉描述,一切都会正常运行。在数据库模型定义中,我定义了如下描述:
description = db.StringProperty(multiline=True)
尝试 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 将其注册为数据库模型中的字符串所需要的。
请您参考如下方法:
>>> u"ü".decode("utf-8")
Unicode编码错误
>>> u"ü".encode("utf-8")
'\xc3\xbc'
>>> u"ü".encode("utf-8").decode("utf-8")
你'\xfc'
>>> str(u"ü".encode("utf-8").decode("utf-8"))
Unicode编码错误
>>> str(u"ü".encode("utf-8"))
'\xc3\xbc'
您需要哪种编码?
您还可以使用:
string2 = cgi.escape(string).encode("latin-1", "xmlcharrefreplace")
这会将所有非 latin-1 字符替换为 xml 实体。
