Heim > Fragen und Antworten > Hauptteil
在python2中用urllib模块去请求淘宝的IP地址查询接口,返回的是一段json字符串,如下所示:
import urllib
def get_data(ip):
url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip
data = urllib.urlopen(url).read()
return data
if __name__ == "__main__":
result = get_data("59.151.5.5")
print(result)
返回结果如下:
{"code":0,"data":{"country":"\u4e2d\u56fd","country_id":"CN","area":"\u534e\u5317","area_id":"100000","region":"\u5317\u4eac\u5e02","region_id":"110000","city":"\u5317\u4eac\u5e02","city_id":"110100","county":"","county_id":"-1","isp":"\u4e16\u7eaa\u4e92\u8054","isp_id":"100021","ip":"59.151.5.5"}}
在返回结果中,中文是以 unicode字符串表示,这样不方便阅读,我想让结果中中文部分直接用中文表示,就像下面这样:
"city":"北京","ISP":"中国电信"
如果是python3的话返回又是这样的:
b'{"code":0,"data":{"country":"\\u4e2d\\u56fd","country_id":"CN","area":"\\u534e\\u5317","area_id":"100000","region":"\\u5317\\u4eac\\u5e02","region_id":"110000","city":"\\u5317\\u4eac\\u5e02","city_id":"110100","county":"","county_id":"-1","isp":"\\u4e16\\u7eaa\\u4e92\\u8054","isp_id":"100021","ip":"59.151.5.5"}}'
请问在 python2和python3中分别该如何转码呢?
伊谢尔伦2017-04-18 10:33:42
Python3中有两个方法可以解决你的问题:
print()函数
Python3开始编码定义为UTF-8,所以你懂的,直接打印就行:
>>> print("\u5317\u4eac\u5e02")
北京市
利用Unicode数据库
有个自带的库unicodedata
,可以调用这个库中的两个方法,如下:
>>> import unicodedata as u
# 这段字符串是来自你给提供的内容
>>> s = "\u5317\u4eac\u5e02"
>>> s1 = ''
>>> for i in s:
s1 += u.lookup(u.name(i))
# 输出结果
>>> s1
'北京市'
补充一下,如果单独处理字符可以用上面的方法,但是刚才回答完才发现你的返回值为byte对象,Python3中这种对象处理很简单,修改你的代码如下:
import urllib.request as r
def get_data(ip):
url = "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip
data = r.urlopen(url).read()
return data
if __name__ == "__main__":
result = get_data("59.151.5.5")
print(eval(result))
我测试完的返回值是:
{'data': {'area_id': '100000', 'isp': '世纪互联', 'country_id': 'CN', 'country': '中国', 'region_id': '110000', 'county_id': '-1', 'ip': '59.151.5.5', 'city': '北京市', 'area': '华北', 'county': '', 'city_id': '110100', 'isp_id': '100021', 'region': '北京市'}, 'code': 0}
希望采纳
天蓬老师2017-04-18 10:33:42
Python 3里你可以通过decode方法把bytes转换str:
result = get_data("59.151.5.5").decode('raw_unicode_escape')
PHPz2017-04-18 10:33:42
这样就好了==
import json
print json.dumps(json.loads(result), ensure_ascii=False)