Py:利用pickle模块和API天气接口实现输入城市得到该城市的天气预报



目录

​输出结果​

​实现代码​




输出结果

Py:利用pickle模块和API天气接口实现输入城市得到该城市的天气预报_数据


 Py:利用pickle模块和API天气接口实现输入城市得到该城市的天气预报_接口实现_02


实现代码

# -*- coding: utf-8 -*-
'''
Created on 2017年3月10日

@author: niu
'''
import urllib.request
import json
import pickle
pickle_file=open("city_data.pkl","rb")
city=pickle.load(pickle_file)

cityname = input("你想查询那个城市的天气?")
citycode=""

try:
citycode =city[cityname]
except:
print ("not Found")
if citycode:
try:
url= "http://www.weather.com.cn/data/cityinfo/"+citycode+".html"#构造网址
content = urllib.request.urlopen(url).read()#读取网页源代码
data =json.loads(content)#使用json库将字符转化为字典
#print type(data)
#print (content)
res =data["weatherinfo"]#获取字典
str_temp=("%s :%s~%s")%(res["weather"],res["temp1"],res["temp2"])#格式化字符
print (str_temp)#输出天气信息
except:
print ("Not Found!!" )


利用子程序将城市数据载入

import pickle
pickle_file=open("city_data.pkl","wb")
pickle.dump(city,pickle_file)
pickle_file.close()


相关文章

Py:利用pickle模块和API天气接口实现输入城市得到该城市的天气预报