您的位置:首页 > 编程语言 > Python开发

python基础教程共60课-第45课查天气3

2015-12-29 10:26 661 查看
python基础教程共60课-第45课查天气3

【Python 第45课】 查天气(3)

看一下我们已经拿到的json格式的天气数据:

{

"weatherinfo": {

"city": "南京",

"cityid": "101190101",

"temp1": "37℃",

"temp2": "28℃",

"weather": "多云",

"img1": "d1.gif",

"img2": "n1.gif",

"ptime": "11:00"

}

}

复制代码

直接在命令行中看到的应该是没有换行和空格的一长串字符,这里我把格式整理了一下。可以看出,它像是一个字典的结构,但是有两层。最外层只有一个key--“weatherinfo”,它的value是另一个字典,里面包含了好几项天气信息,现在我们最关心的就是其中的temp1,temp2和weather。

虽然看上去像字典,但它对于程序来说,仍然是一个字符串,只不过是一个满足json格式的字符串。我们用python中提供的另一个模块json提供的loads方法,把它转成一个真正的字典。

import json

data = json.loads(content)

复制代码

这时候的data已经是一个字典,尽管在控制台中输出它,看上去和content没什么区别,只是编码上有些不同:

{u'weatherinfo': {u'city': u'\u5357\u4eac', u'ptime': u'11:00', u'cityid': u'101190101', u'temp2': u'28\u2103', u'temp1': u'37\u2103', u'weather': u'\u591a\u4e91', u'img2': u'n1.gif', u'img1': u'd1.gif'}}

复制代码

但如果你用type方法看一下它们的类型:

print type(content)

print type(data)

复制代码

就知道区别在哪里了。

之后的事情就比较容易了。

result = data['weatherinfo']

str_temp = ('%s\n%s ~ %s') % (

result['weather'],

result['temp1'],

result['temp2']

)

print str_temp

复制代码

为了防止在请求过程中出错,我加上了一个异常处理。

try:

###

###

except:

print '查询失败'

复制代码

以及没有找到城市时的处理:

if citycode:

###

###

else:

print '没有找到该城市'

复制代码

完整代码:

# -*- coding: utf-8 -*-

import urllib2

import json

from city import city

cityname = raw_input('你想查哪个城市的天气?\n')

citycode = city.get(cityname)

if citycode:

try:

url = ('http://www.weather.com.cn/data/cityinfo/%s.html'

% citycode)

content = urllib2.urlopen(url).read()

data = json.loads(content)

result = data['weatherinfo']

str_temp = ('%s\n%s ~ %s') % (

result['weather'],

result['temp1'],

result['temp2']

)

print str_temp

except:

print '查询失败'

else:

print '没有找到该城市'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: