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

python获取城市天气情况案例

2015-02-11 22:34 369 查看
我主要是参考中国开源社区OSchina上的源码进行学习http://www.oschina.net/code/snippet_946290_45838

非常感谢原作者),我将每个步骤分别进行讲解,比原作者更加详细

源码如下:

__author__ = 'dyb'

import os
import urllib.request
import urllib.parse
import json

class weather(object):

# 获取城市代码的uri
citycode_uri = "http://apistore.baidu.com/microservice/cityinfo?cityname="

# 获取天气信息的uri
weather_uri = "http://apistore.baidu.com/microservice/weather?cityid="

#主要业务逻辑处理
def mainHandle(self):
print("输入你要查询天气的城市:")
city_name = input()
uri = self.citycode_uri + urllib.parse.quote(city_name)
ret = json.loads(urllib.request.urlopen(uri).read().decode("utf8"))
if(ret['errNum']) != 0:
print('网络或者服务器出错')
return False
else:
weather_uri = self.weather_uri + ret['retData']['cityCode']
data = json.loads(urllib.request.urlopen(weather_uri).read().decode("utf8"))
if data['errNum'] == 0:
ret_data = data['retData']
output = "城市名:" + ret_data['city'] + "\r\n"
output += "更新时间:" + ret_data["date"] + " " + ret_data["time"] + "\r\n"
output += "城市编码:" + ret_data['citycode'] + "\r\n"
output += "经度:" + str(ret_data['longitude']) + "\r\n"
output += "维度:" + str(ret_data['latitude']) + "\r\n"
output += "邮编:" + ret_data['postCode'] + "\r\n"
output += "海拔:" + ret_data['altitude'] + "\r\n"
output += "天气情况:" + ret_data["weather"] + "\r\n"
output += "温度:" + ret_data["temp"] + "\r\n"
output += "最低气温:" + ret_data['l_tmp'] + "\r\n"
output += "最高气温:" + ret_data['h_tmp'] + "\r\n"
output += "风向:" + ret_data['WD'] + "\r\n"
output += "风力:" + ret_data['WS'] + "\r\n"
output += "日出时间:" + ret_data['sunrise'] + "\r\n"
output += "日落时间:" + ret_data['sunset'] + "\r\n"
print(output)
return True
else:
print('网络或者服务器出错')
return False

if __name__ == "__main__":
weather = weather()
weather.mainHandle()


首先是程序入口:

__name__ == "__main__"

模块是对象,并且所有的模块都有一个内置属性 __name__。一个模块的 __name__ 的值取决于您如何应用模块。如果 import 一个模块,那么模块__name__ 的值通常为模块文件名,不带路径或者文件扩展名。但是您也可以像一个标准的程序样直接运行模块,在这
种情况下, __name__ 的值将是一个特别缺省"__main__"。

在cmd 中直接运行.py文件,则__name__的值是'__main__';

而在import 一个.py文件后,__name__的值就不是'__main__'了;

从而用if __name__ == '__main__'来判断是否是在直接运行该.py文件

如:

#Test.py
class Test:
def __init(self):pass
def f(self):print 'Hello, World!'
if __name__ == '__main__':
Test().f()
#End


你在cmd中输入:

C:>python Test.py

Hello, World!

说明:"__name__ == '__main__'"是成立的

你再在cmd中输入:

C:>python

>>>import Test

>>>Test.__name__ #Test模块的__name__

'Test'

>>>__name__ #当前程序的__name__

'__main__'

以北京为例:

>>>

输入你要查询天气的城市:

北京

上面的ret输出的结果是:

{'errNum': 0, 'retMsg': 'success', 'retData': {'zipCode': '100000', 'cityName': '北京', 'provinceName': '北京', 'telAreaCode': '010', 'cityCode': '101010100'}}

可以通过ret['errNum']这样的方式来获取json中各个对应的数据,如果这里不明白建议看下Python的元组、数组、映射(map)等相关知识

ret['errNum'] =0为成功=-1为失败

程序中变量data的输出值也是json格式,获取方式相同:

{'errNum': 0, 'errMsg': 'success', 'retData': {'temp': '-4', 'time': '18:00', 'citycode': '101010100', 'city': '北京', 'l_tmp': '', 'WD': '无持续风向', 'date': '15-02-11', 'postCode': '100000', 'pinyin': 'beijing', 'altitude': '33', 'sunrise': '07:12', 'weather':
'晴', 'longitude': 116.391, 'WS': '微风(<10m/h)', 'sunset': '17:44', 'h_tmp': '-4', 'latitude': 39.904}}

JSON返回示例:

{

errNum: 0,

errMsg: "success",

retData: {

city: "北京", //城市

pinyin: "beijing", //城市拼音

citycode: "101010100", //城市编码

date: "15-02-11", //日期

time: "11:00", //发布时间

postCode: "100000", //邮编

longitude: 116.391, //经度

latitude: 39.904, //维度

altitude: "33", //海拔

weather: "晴", //天气情况

temp: "10", //气温

l_tmp: "-4", //最低气温

h_tmp: "10", //最高气温

WD: "无持续风向", //风向

WS: "微风(<10m/h)", //风力

sunrise: "07:12", //日出时间

sunset: "17:44" //日落时间

}

}

output为输出语句,当输出经度和纬度的时候它们的格式是float类型,所以需要转换成str类型才能拼接在一起,使用str()函数

具体关于参数请参考天气的API介绍:http://apistore.baidu.com/astore/serviceinfo/1798.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: