获取城市天气的Python脚本

获取城市天气的Python脚本,第1张

概述获取城市天气的Python脚本

下面是内存溢出 jb51.cc 通过网络收集整理的代码片段。

内存溢出小编现在分享给大家,也给大家做个参考。

原文  http://xianglong.me/article/get-city-weather-using-python-script/
#!/usr/bin/env python# -*- Coding: utf-8 -*-# import requestsimport urllibimport Jsonimport sysfrom datetime import datetime,timedeltabase_url = "http://API.worlDWeatheronline.com/free/v2/weather.ashx"codes = {'113': 'iconSunny','116': 'iconPartlyCloudy',"119": 'iconCloudy','122': 'iconVeryCloudy','143': 'iconFog','176': 'iconlightShowers','179': 'iconlightSleetShowers','182': 'iconlightSleet','185': 'iconlightSleet','200': 'iconThunderyShowers','227': 'iconlightSNow','230': 'iconHeavySNow','248': 'iconFog','260': 'iconFog','263': 'iconlightShowers','266': 'iconlightRain','281': 'iconlightSleet','284': 'iconlightSleet','293': 'iconlightRain','296': 'iconlightRain','299': 'iconHeavyShowers','302': 'iconHeavyRain','305': 'iconHeavyShowers','308': 'iconHeavyRain','311': 'iconlightSleet','314': 'iconlightSleet','317': 'iconlightSleet','320': 'iconlightSNow','323': 'iconlightSNowShowers','326': 'iconlightSNowShowers','329': 'iconHeavySNow','332': 'iconHeavySNow','335': 'iconHeavySNowShowers','338': 'iconHeavySNow','350': 'iconlightSleet','353': 'iconlightShowers','356': 'iconHeavyShowers','359': 'iconHeavyRain','362': 'iconlightSleetShowers','365': 'iconlightSleetShowers','368': 'iconlightSNowShowers','371': 'iconHeavySNowShowers','374': 'iconlightSleetShowers','377': 'iconlightSleet','386': 'iconThunderyShowers','389': 'iconThunderyHeavyRain','392': 'iconThunderySNowShowers','395': 'iconHeavySNowShowers'     }icons = {  'iconSunny': [    '3[38;5;226m	\   /	3[0m','3[38;5;226m	 .-.	 3[0m','3[38;5;226m  ― (   ) ―  3[0m','3[38;5;226m	 `-’	 3[0m','3[38;5;226m	/   \	3[0m'],'iconPartlyCloudy': [    "3[38;5;226m   \  /3[0m	  ","3[38;5;226m _ /\"\"3[38;5;250m.-.	3[0m","3[38;5;226m   \_3[38;5;250m(   ).  3[0m","3[38;5;226m   /3[38;5;250m(___(__) 3[0m","			 "],'iconCloudy': [    "			 ","3[38;5;250m	 .--.	3[0m","3[38;5;250m  .-(	).  3[0m","3[38;5;250m (___.__)__) 3[0m",'iconVeryCloudy': [    "			 ","3[38;5;240;1m	 .--.	3[0m","3[38;5;240;1m  .-(	).  3[0m","3[38;5;240;1m (___.__)__) 3[0m",'iconlightShowers': [    "3[38;5;226m _`/\"\"3[38;5;250m.-.	3[0m","3[38;5;226m,\_3[38;5;250m(   ).  3[0m","3[38;5;111m	 ‘ ‘ ‘ ‘ 3[0m","3[38;5;111m	‘ ‘ ‘ ‘  3[0m"],'iconHeavyShowers': [    "3[38;5;226m _`/\"\"3[38;5;240;1m.-.	3[0m",\_3[38;5;240;1m(   ).  3[0m","3[38;5;226m   /3[38;5;240;1m(___(__) 3[0m","3[38;5;21;1m   ‚‘‚‘‚‘‚‘  3[0m","3[38;5;21;1m   ‚’‚’‚’‚’  3[0m"],'iconlightSNowShowers': [    "3[38;5;226m _`/\"\"3[38;5;250m.-.	3[0m","3[38;5;255m	 *  *  * 3[0m","3[38;5;255m	*  *  *  3[0m"],'iconHeavySNowShowers': [    "3[38;5;226m _`/\"\"3[38;5;240;1m.-.	3[0m","3[38;5;255;1m	* * * *  3[0m","3[38;5;255;1m   * * * *   3[0m"],'iconlightSleetShowers': [    "3[38;5;226m _`/\"\"3[38;5;250m.-.	3[0m","3[38;5;111m	 ‘ 3[38;5;255m*3[38;5;111m ‘ 3[38;5;255m* 3[0m","3[38;5;255m	*3[38;5;111m ‘ 3[38;5;255m*3[38;5;111m ‘  3[0m"],'iconThunderyShowers': [    "3[38;5;226m _`/\"\"3[38;5;250m.-.	3[0m","3[38;5;228;5m	⚡3[38;5;111;25m‘ ‘3[38;5;228;5m⚡3[38;5;111;25m‘ ‘ 3[0m",'iconThunderyHeavyRain': [    "3[38;5;240;1m	 .-.	 3[0m","3[38;5;240;1m	(   ).   3[0m","3[38;5;240;1m   (___(__)  3[0m","3[38;5;21;1m  ‚‘3[38;5;228;5m⚡3[38;5;21;25m‘‚3[38;5;228;5m⚡3[38;5;21;25m‚‘   3[0m","3[38;5;21;1m  ‚’‚’3[38;5;228;5m⚡3[38;5;21;25m’‚’   3[0m"],'iconThunderySNowShowers': [    "3[38;5;226m _`/\"\"3[38;5;250m.-.	3[0m","3[38;5;255m	 *3[38;5;228;5m⚡3[38;5;255;25m *3[38;5;228;5m⚡3[38;5;255;25m * 3[0m",'iconlightRain': [    "3[38;5;250m	 .-.	 3[0m","3[38;5;250m	(   ).   3[0m","3[38;5;250m   (___(__)  3[0m","3[38;5;111m	‘ ‘ ‘ ‘  3[0m","3[38;5;111m   ‘ ‘ ‘ ‘   3[0m"],'iconHeavyRain': [    "3[38;5;240;1m	 .-.	 3[0m","3[38;5;21;1m  ‚‘‚‘‚‘‚‘   3[0m","3[38;5;21;1m  ‚’‚’‚’‚’   3[0m"],'iconlightSNow': [    "3[38;5;250m	 .-.	 3[0m","3[38;5;255m	*  *  *  3[0m","3[38;5;255m   *  *  *   3[0m"],'iconHeavySNow': [    "3[38;5;240;1m	 .-.	 3[0m","3[38;5;255;1m   * * * *   3[0m","3[38;5;255;1m  * * * *	3[0m"],'iconlightSleet': [    "3[38;5;250m	 .-.	 3[0m","3[38;5;111m	‘ 3[38;5;255m*3[38;5;111m ‘ 3[38;5;255m*  3[0m","3[38;5;255m   *3[38;5;111m ‘ 3[38;5;255m*3[38;5;111m ‘   3[0m"],'iconFog': [    "			 ","3[38;5;251m _ - _ - _ - 3[0m","3[38;5;251m  _ - _ - _  3[0m",'iconUnkNown': [    "	.-.	  ","	 __)	 ","	(		","	 `-’	 ","	  •	  "]  }windDir = {  "N":   "3[1m↓3[0m","NNE": "3[1m↓3[0m","NE":  "3[1m↙3[0m","ENE": "3[1m↙3[0m","E":   "3[1m←3[0m","ESE": "3[1m←3[0m","SE":  "3[1m↖3[0m","SSE": "3[1m↖3[0m","S":   "3[1m↑3[0m","SSW": "3[1m↑3[0m","SW":  "3[1m↗3[0m","WSW": "3[1m↗3[0m","W":   "3[1m→3[0m","WNW": "3[1m→3[0m","NW":  "3[1m↘3[0m","NNW": "3[1m↘3[0m",}class query(object):    def __init__(self,day,city):        self.day = day        self.time = [3,4,5,6]        self.weatherCode = ''        self.weather = ''        self.date = ''        self.hourly = ''        self.tempC = 0        self.winddir16Point = ''        self.windspeedKmph = 0        self.humIDity = 0        self.chanceofwater = 0        self.city = city    def query(self):        # 使用resquests        # p={"q":"%s"%self.city,"num_of_days":3,"format":"Json","key":"55f1fdd05fba23be0a18043d0a017","lang":"zh"}        # response=requests.get(base_url,params=p)        # Json_string = response.text        #使用urllib        url = base_url + "?key=55f1fdd05fba23be0a18043d0a017&q=%s#_of_days=3&format=Json⟨=zh" % self.city        response = urllib.urlopen(url)        Json_string = response.read()        parsed_Json = Json.loads(Json_string)        data = parsed_Json['data']			  # 获取所有数据        try:            self.weather = data['weather'][self.day]			# 获取天气预报,[]内0代表当天,1代表明天,以此类推。        except KeyError:            print "3[1;31;49m" + "请输入正确的城市或地区!" + "3[0m"            sys.exit()        self.date = self.weather['date']    def detail(self,time):        self.hourly = self.weather['hourly'][time]		   # 获取小时数据,time:100-1500        self.weatherCode = self.hourly['weatherCode']        self.tempC = self.hourly['tempC']        self.winddir16Point = self.hourly['winddir16Point']        self.windspeedKmph = self.hourly['windspeedKmph']        self.chanceofrain = self.hourly['chanceofrain']        self.chanceofsNow = self.hourly['chanceofsNow']        self.humIDity = self.hourly['humIDity']        self.chanceofwater = int(self.chanceofrain) if int(self.chanceofrain) > int(self.chanceofsNow) else int(self.chanceofsNow)    def printSingle(self):        l1 = l2 = l3 = l4 = l5 = ''        for time in self.time:            self.detail(time)            l1 += '│' + icons[codes[self.weatherCode]][0] + self.hourly['lang_zh'][0]['value'].encode("utf-8") + '\t\t' if len(self.hourly['lang_zh'][0]['value'].encode("utf-8")) <= 12 else '│' + icons[codes[self.weatherCode]][0] + self.hourly['lang_zh'][0]['value'].encode("utf-8") + '\t'            l2 += '│' + icons[codes[self.weatherCode]][1] + temp_color(self.tempC) + "°C"+'\t\t'            l3 += '│' + icons[codes[self.weatherCode]][2] + windDir[self.winddir16Point]+" "+ wind_color(self.windspeedKmph) + "km/h" + '\t\t'            l4 += '│' + icons[codes[self.weatherCode]][3] + "降水概率:" + str(self.chanceofwater) + "%" + '\t'            l5 += '│' + icons[codes[self.weatherCode]][4] + "湿度:" + str(self.humIDity) + "%" + '\t\t'        print l1+"│"        print l2+"│"        print l3+"│"        print l4+"│"        print l5+"│"    def printDay(self,delta):        date_time = datetime.strftime(datetime.today() + timedelta(days=delta),"%Y-%m-%d")        line1 = "														 ┌─────────────┐													   "        line2 = "┌───────────────────────────────┬──────────────────────────%s───────────────────────────┬───────────────────────────────┐" % date_time        line3 = "│		   Morning			 │			 Noon	   └──────┬──────┘	Evening			 │			Night			  │"        line4 = "├───────────────────────────────┼───────────────────────────────┼───────────────────────────────┼───────────────────────────────┤"        endline= "└───────────────────────────────┴───────────────────────────────┴───────────────────────────────┴───────────────────────────────┘"        print line1        print line2        print line3        print line4        self.printSingle()        print endlinedef temp_color(temp):    if temp >= 35 or temp <= -10:        color = "3[1;31;49m" + str(temp) + "3[0m"    elif (temp >= 25 and temp <35):        color = "3[1;33;49m" + str(temp) + "3[0m"    elif temp > 10 and temp < 25:        color = "3[1;32;49m" + str(temp) + "3[0m"    elif temp >-10 and temp <= 10:        color = "3[1;34;49m" + str(temp) + "3[0m"    return colordef wind_color(windspeed):    if windspeed <= 5:        color = "3[1;32;49m" + str(windspeed) + "3[0m"    elif windspeed > 5 and windspeed <=10:        color = "3[1;33;49m" + str(windspeed) + "3[0m"    else:        color = "3[1;34;49m" + str(windspeed) + "3[0m"    return colordef main():    try:        city = sys.argv[1]    except IndexError:        print "3[1;31;49m" + "请输入您要查询的城市或地区:" + "3[0m"        city = raw_input()        if city == '':            sys.exit()    day = [0,1,2]    for i in day:        query = query(i,city)        query.query()        query.printDay(i)if __name__ == "__main__":    main()

以上是内存溢出(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

总结

以上是内存溢出为你收集整理的获取城市天气的Python脚本全部内容,希望文章能够帮你解决获取城市天气的Python脚本所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1198654.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存