分享

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

 处女座的程序猿 2021-09-28

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


输出结果

 

实现代码

# -*- 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天气接口实现输入城市得到该城市的天气预报
 

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多