|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 太阳雨 于 2014-5-17 10:39 编辑
各位鱼油们,大家好,今天学习了easygui,就把之前的天气预报的代码优化了一下,和大家交流一下
有图有真相
输入城市名
天气情况
城市信息不存在
网路错误
- #encoding: utf-8
- import urllib.request
- import json
- import pickle
- import os
- import sys
- import easygui as eg
- sys.path.append(r'C:\Python34\Lib\site-packages')
- #获取程序运行目录
- def current_file_directory():
- import os, sys, inspect
- path = os.path.realpath(sys.path[0]) # interpreter starter's path
- if os.path.isfile(path): # starter is excutable file
- path = os.path.dirname(path)
- return os.path.abspath(path) # return excutable file's directory
- else: # starter is python script
- caller_file = inspect.stack()[1][1] # function caller's filename
- return os.path.abspath(os.path.dirname(caller_file))# return function caller's
- def jsoncall(url):
- url_file = urllib.request.urlopen(url)
- weatherHTML = url_file.read().decode('utf-8')
- weatherJSON = json.JSONDecoder().decode(weatherHTML)
- return weatherJSON
- pkl_city = open("{path}\\city.pkl".format(path=current_file_directory()),"rb")
- city = pickle.load(pkl_city)
- pkl_city.close()
- #city_name = input('请输入城市名:')
- while True:
- city_name = eg.enterbox(msg='请输入城市名', title='天气情况查询',default='天津',strip=True)
- #用户直接取消查询,系统退出
- if city_name == None:
- sys.exit(0)
- password = city.get(city_name)
- #输入城市不存在
- if password == None:
- choice = eg.boolbox(msg='您所输入的城市不存在,是否继续查询', title='城市信息不存在')
- if choice:
- continue
- else:
- sys.exit(0)
- else:
- break
- try:
- url_file_name = 'http://www.weather.com.cn/data/sk/{password}.html'.format(password=password)
- weatherInfo = jsoncall(url_file_name)['weatherinfo']
- url_file_name = 'http://www.weather.com.cn/data/cityinfo/{password}.html'.format(password=password)
- weatherInfo2 = jsoncall(url_file_name)['weatherinfo']
- except:
- eg.msgbox(msg='请您检查您的网络', title='无可用网络')
- sys.exit(0)
- #http://m.weather.com.cn/img/ 图片地址
- msg='城市:{city}\n播报时间:{time}\n天气:{weather}\n室外温度:{temp}℃\n温度:{lower}-{high}\n风力:{wind}{level}'.format(
- city=weatherInfo.get('city'),
- time=weatherInfo.get('time'),
- weather=weatherInfo2.get('weather'),
- temp=weatherInfo.get('temp'),
- lower=weatherInfo2.get('temp2'),
- high=weatherInfo2.get('temp1'),
- wind=weatherInfo.get('WD'),
- level=weatherInfo.get('WS'))
- eg.msgbox(msg=msg,title='今日{city_name}天气情况'.format(city_name=city_name))
复制代码
源代码下载:
|
评分
-
查看全部评分
|