[英]GAE Python: Importing UTF-8 Characters from an XML file to a database model
我正在從在線來源解析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')
我從中得到的錯誤顯示在下面。 這是由描述字段中的“ü”引起的,稍后在使用數據時我還將需要顯示它。
在get coupon.description = str(voucher.getElementsByTagName(“ Description”)[0] .firstChild.data.decode中的文件“ C:\\ Users \\ Vincent \\ Documents \\ www \\ Sparkompass \\ Website \\ main.py”中,第217行('utf-8'))文件“ C:\\ Python27 \\ lib \\ encodings \\ utf_8.py”,第16行,解碼返回codecs.utf_8_decode(input,errors,True)UnicodeEncodeError:'ascii'編解碼器無法編碼字符u'\\ xfc'在位置16:序數不在范圍內(128)
如果我刪除說明,一切都會正常進行。 在數據庫模型定義中,我將描述定義如下:
description = db.StringProperty(multiline=True)
嘗試2
我也試圖這樣做:
coupon.description = str(voucher.getElementsByTagName("Description")[0].firstChild.data).decode('utf-8')
這也給了我:
UnicodeEncodeError:'ascii'編解碼器無法在位置16編碼字符u'\\ xfc'(序數不在范圍內)(128)
任何幫助將不勝感激!
UPDATE
XML文件包含德語,這意味着其中的更多字符都是UTF-8字符。 因此,理想情況下,我現在正在考慮最好在較高級別(例如在
xml = parseString(url.content)
但是到目前為止,我也沒有做到這一點。 目的是獲取ascii中的字符,因為這是GAE要求將其注冊為數據庫模型中的字符串。
>>> u"ü".decode("utf-8")
UnicodeEncodeError
>>> u"ü".encode("utf-8")
'\\ XC3 \\命苦'
>>> u"ü".encode("utf-8").decode("utf-8")
U '\\ XFC'
>>> str(u"ü".encode("utf-8").decode("utf-8"))
UnicodeEncodeError
>>> str(u"ü".encode("utf-8"))
'\\ XC3 \\命苦'
您需要哪種編碼?
您還可以使用:
string2 = cgi.escape(string).encode("latin-1", "xmlcharrefreplace")
這會將所有非拉丁1字符替換為xml實體。
我現在通過將描述更改為TextProperty來解決該問題,該操作沒有任何錯誤。 我知道我在執行此操作時將無法進行排序或過濾,但出於描述的考慮,這應該可以。
背景信息: https : //developers.google.com/appengine/docs/python/datastore/typesandpropertyclasses#TextProperty
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.