题
即时尝试从API检索坐标,但其中一个JSON对象包含丹麦语字母,我继续出错。这就是我所拥有的:
# -*- coding: utf-8 -*-
import urllib2
import json
import codecs
url='http://geo.oiorest.dk/adresser.json?postnr=1577&vejnavn=bernstorffsgade&husnr=16'
addressline = "%s, %s"
try:
data = urllib2.urlopen(url).read().decode('utf-8')
adresser = json.loads(data, encoding='utf-8')
for adresse in adresser:
print addressline % \
(adresse['etrs89koordinat']['øst'],
adresse['etrs89koordinat']['nord'])
except urllib2.HTTPError, e:
print "HTTP error: %d" % e.code
except urllib2.URLError, e:
print "Network error: %s" % e.reason.args[1]
.
我得到的错误:
KeyError: '\xc3\xb8st'
. 解决方案
您的解码数据包含Unicode字符串,因此您需要使用Unicode字符串查找:
print addressline % \
(adresse[u'etrs89koordinat'][u'øst'],
adresse[u'etrs89koordinat'][u'nord'])
.
(您可能会发现它适用于只包含Uncode字符串的字符串,无论是Unicode字符串,是否仅包含Unicode字符串,因为Unicode和默认编码之间的自动转换,但这不会用于重音字符。)
不隶属于 StackOverflow