gpt4 book ai didi

python - 解码编码为GB2312的json

转载 作者:行者123 更新时间:2023-11-28 22:00:58 25 4
gpt4 key购买 nike

通过 GET 请求,我从 Google geocode API 中提取 json:

import urllib, urllib2

url = "http://maps.googleapis.com/maps/api/geocode/json"
params = {'address': 'ivory coast', 'sensor': 'false'}
request = urllib2.Request(url + "?" + urllib.urlencode(params))
response = urllib2.urlopen(request)
st = response.read()

结果看起来像:

{
"results" : [
{
"address_components" : [
{
"long_name" : "Côte d'Ivoire",
"short_name" : "CI",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Côte d'Ivoire",
"geometry" : { ... # rest snipped

如您所见,国家名称存在一些编码问题。我试着猜测这样的编码:

import chardet
encoding = chardet.detect(st)
print "String is encoded in {0} (with {1}% confidence).".format(encoding['encoding'], encoding['confidence']*100)

哪个返回:

String is encoded in GB2312 (with 99.0% confidence).

我想知道的是如何将其转换为具有正确显示 ô(o with circumflex)编码的字典。

我试过:

st = st.decode(encoding['encoding']).encode('utf-8')

但后来我得到:

{
"results" : [
{
"address_components" : [
{
"long_name" : "C么te d'Ivoire",
"short_name" : "CI",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "C么te d'Ivoire",
"geometry" : { ... # rest snipped

最佳答案

google api 结果始终以 UTF-8 编码,您甚至可以从其 HTTP Content-Type header 中手动读取:

enter image description here

关于python - 解码编码为GB2312的json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13958196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com