ubuntu下python3.6输出汉字显示为'\xe6\x98\x8c\xe5\xb9\xb3'
python3版本对文本和二进制作了更清晰的区分.文本是unicode,由str类型表示,二进制则由bytes类型表示.引起上述问题就是要输出的内容为bytes类型,需要把它转换为str类型.
可以通过 type() 查看对象的数据的类型
如
url = (‘http://www.weather.com.cn/data/cityinfo/%s.html’
% citycode)
response = urllib.request.urlopen(url).read()
print(type(response))
print(response)
会打印出’{“weatherinfo”:{“city”:"\xe6\x98\x8c\xe5\xb9\xb3",“cityid”:“101010700”,“temp1”:“17\xe2\x84\x83”,“temp2”:“29\xe2\x84\x83”,“weather”:"\xe5\xa4\x9a\xe4\xba\x91\xe8\xbd\xac\xe9\x98\xb4",“img1”:“n1.gif”,“img2”:“d2.gif”,“ptime”:“18:00”}}’
<class ‘bytes’>
代码修改为:
url = (‘http://www.weather.com.cn/data/cityinfo/%s.html’
% citycode)
response = urllib.request.urlopen(url).read()
response1 = response.decode() #utf-8默认不填写,如果是其他编码就填写参数 如decode(‘gb2312’)
print(type(response1))
print(response1)
这时候就能输出你想要的结果了
{“weatherinfo”:{“city”:“昌平”,“cityid”:“101010700”,“temp1”:“17℃”,“temp2”:“29℃”,“weather”:“多云转阴”,“img1”:“n1.gif”,“img2”:“d2.gif”,“ptime”:“18:00”}}
<class ‘str’>
第一次写博客,有点小激动哈哈,可能我自己都不知道自己讲的是什么,以后慢慢改进.虽然这只是一个小问题,但也是浪费了我一些时间.贴在这里,以供以后用.