python读取文件求气温平均值_使用python遍历指定城市的一周气温

该程序使用Python遍历指定城市(如保定、北京、上海等)的一周天气预报,将数据从摄氏度转换为华氏度进行显示。通过调用API获取JSON数据,然后解析和处理数据,展示每天的最高和最低气温。
摘要由CSDN通过智能技术生成

处于兴趣,写了一个遍历指定城市五天内的天气预报,并转为华氏度显示。

把城市名字写到一个列表里这样可以方便的添加城市。并附有详细注释 import requests

import json

#定义一个函数 避免代码重写多次。

def gettemp(week,d_or_n,date):

wendu=data['result']['weather'][week]['info'][d_or_n][date] #对字典进行拆分

return int(wendu)

def getft(t):

ft=t*1.8+32

return float(str(ft)[0:4])

cities=['保定','北京','上海','武汉','郑州','齐齐哈尔'] #这里可以指定想要遍历的城市

url='http://api.avatardata.cn/Weather/Query?key=68e75677978441f6872c1106175b8673&cityname=' #用于和cities里的城市进行字符串拼接

low=0

high=2

for city in cities:

r = requests.get(url+city) # 最基本的GET请求

#print(r.status_code) 获取返回状态200是成功

#print(r.text) 打印解码后的返回数据

data=json.loads(r.text) #返回的json数据被转换为字典类型

#print(type(data)) data 的数据类型是字典 所以可以按照字典操作(字典里的列表就按列表操作)

print(city,'近五天天气预报:')

for i in range(5):

week='周'+str(data['result']['weather'][i]['week']) #对字典类型进行逐个拆分 如列表 元组等。

daylow=gettemp(i,'day',low)

dlf=getft(daylow)

dayhigh=gettemp(i,'day',high)

dhf=getft(dayhigh)

nightlow=gettemp(i,'night',low)

nlf=getft(nightlow)

nighthigh=gettemp(i,'night',high)

nhf=getft(nighthigh)

print(week,'白天气温:',daylow,'~',dayhigh,'摄氏度','晚上气温:',nightlow,'~',nighthigh,'摄氏度')

print(' ','白天气温:',dlf,'~',dhf,'华氏度','晚上气温:',nlf,'~',nhf,'华氏度')

print('\n')

{"result":{"realtime":{"wind":{"windspeed":null,"direct":"西风","power":"3级","offset":null},"time":"16:00:00","weather":{"humidity":"27","img":"0","info":"晴","temperature":"13"},"dataUptime":"1490517362","date":"2017-03-26","city_code":"101090201","city_name

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值