unicode解码的问题

Ste*_*ini 4 python encoding utf-8 iso-8859-1 latin1

这很有趣..我正在尝试从openstreetmap读取地理查找数据.执行查询的代码如下所示

params = urllib.urlencode({'q': ",".join([e for e in full_address]), 'format': "json", "addressdetails" : "1"})
query = "http://nominatim.openstreetmap.org/search?%s" % params
print query
time.sleep(5)
response = json.loads(unicode(urllib.urlopen(query).read(), "UTF-8"), encoding="UTF-8")
print response
Run Code Online (Sandbox Code Playgroud)

对Zürich的查询在UTF-8数据上进行了正确的URL编码.这里没有奇迹.

http://nominatim.openstreetmap.org/search?q=Z%C3%BCrich%2CSWITZERLAND&addressdetails=1&format=json
Run Code Online (Sandbox Code Playgroud)

当我打印响应时,带有变音符号的u被编码为latin1(0xFC)

[{u'display_name': u'Z\xfcrich, Bezirk Z\xfcrich, Z\xfcrich, Schweiz, Europe', u'place_id': 588094, u'lon': 8.540443
Run Code Online (Sandbox Code Playgroud)

但这是无稽之谈,因为openstreetmap以UTF-8返回JSON数据

Connecting to nominatim.openstreetmap.org (nominatim.openstreetmap.org)|128.40.168.106|:80... connected.
HTTP request sent, awaiting response... 
  HTTP/1.1 200 OK
  Date: Wed, 26 Jan 2011 13:48:33 GMT
  Server: Apache/2.2.14 (Ubuntu)
  Content-Location: search.php
  Vary: negotiate
  TCN: choice
  X-Powered-By: PHP/5.3.2-1ubuntu4.7
  Access-Control-Allow-Origin: *
  Content-Length: 3342
  Keep-Alive: timeout=15, max=100
  Connection: Keep-Alive
  Content-Type: application/json; charset=UTF-8
Length: 3342 (3.3K) [application/json]
Run Code Online (Sandbox Code Playgroud)

这也是由文件内容确认的,然后我明确地说它在读取和json解析时都是UTF-8.

这里发生了什么 ?

编辑:显然这是json.loads以某种方式搞砸了.

eta*_*ion 8

当我去打印响应时,带有变音符号的u被编码为latin1(0xFC)

你只是误解了输出.它是一个unicode字符串(你可以通过前缀中的u来判断),没有编码"附加" - \xFC意味着它是编号为0xFC的代码点,恰好是U-Umlaut(参见http:// www. fileformat.info/info/unicode/char/fc/index.htm).发生这种情况的原因是前256个unicode代码点的编号与latin1编码一致.

简而言之,你做的一切都是正确的 - 你有一个具有正确内容的unicode对象(与编码无关),你可以通过执行unicodestr.encode("utf-8"来选择使用该内容进行输出时所需的编码. ")或使用编解码器,请参阅http://docs.python.org/howto/unicode.html#reading-and-writing-unicode-data

  • @Pekka:Python不使用UTF-8进行内部字符串表示.`00FC`是`ü`的Unicode代码点,正如@etarion所解释的那样.当你将它编码为UTF-8时,它将被改为`b"\ xc3\xbc"`,但只有这样.`\ xfc`与`\ u00fc`相同. (2认同)