[Python高效编程] - 获取天气信息并使用迭代for输出
2017-11-23 20:54
866 查看
开发环境
Python版本: python3.6调试工具:pycharm 2017.1.3
电脑系统:Windows 10 64位系统
Python库:requests,collections
获取天气信息
import requests def getWeather(city): r = requests.get("http://wthrcdn.etouch.cn/weather_mini?city=" + city) data = r.json()['data']['forecast'][0] return '{0}: {1}, {2}'.format(city, data['low'], data['high']) print(getWeather('武汉'))
武汉: 低温 4℃, 高温 15℃
使用可迭代对象和迭代器输出信息
from collections import Iterable, Iterator import requests class WeatherIterator(Iterator): # 继承可迭代的对象 def __init__(self, cities): self.cities = cities self.index = 0 def getWeather(self, city): r = requests.get("http://wthrcdn.etouch.cn/weather_mini?city=" + city) data = r.json()['data']['forecast'][0] return '{0}: {1}, {2}'.format(city, data['low'], data['high']) def __next__(self): if self.index == len(self.cities): raise StopIteration city = self.cities[self.index] self.index += 1 return self.getWeather(city) class WeatherIterable(Iterable): # 继承迭代器 def __init__(self, cities): self.cities = cities def __iter__(self): return WeatherIterator(self.cities) for x in WeatherIterable(['北京', '上海', '武汉', '深圳']): print(x)
北京: 低温 -4℃, 高温 7℃ 上海: 低温 5℃, 高温 13℃ 武汉: 低温 4℃, 高温 15℃ 深圳: 低温 13℃, 高温 19℃
代码优化
上述的代码还是不够简洁,还可以进一步优化,下面重写代码import requests class WeatherOutput: """输出天气信息""" def __init__(self, cities): self.cities = cities self.index = 0 def getWeather(self, city): try: r = requests.get("http://wthrcdn.etouch.cn/weather_mini?city=" + city) data = r.json()['data']['forecast'][0] return '{0}: {1}, {2}'.format(city, data['low'], data['high']) except: print("获取天气信息失败") def __iter__(self): return self def __next__(self): if self.index == len(self.cities): raise StopIteration city = self.cities[self.index] self.index += 1 return self.getWeather(city) for x in WeatherOutput(['北京', '上海', '武汉', '深圳']): print(x)
北京: 低温 -4℃, 高温 7℃ 上海: 低温 8℃, 高温 14℃ 武汉: 低温 4℃, 高温 17℃ 深圳: 低温 15℃, 高温 19℃
如果想知道原理,可以参考这篇博客:
http://blog.csdn.net/lanhaixuanvv/article/details/78503325
相关文章推荐
- Python网络编程 获取页面中的天气信息
- 树莓派使用Python3获取天气信息
- Python网络编程小例子:使用python获取网站域名信息
- 初学Python的学习笔记9----面向对象编程(获取对象信息、实例属性和类属性)、面向对象高级编程(使用__slots__、使用@property)
- Python学习:使用boost c++嵌入python,获取异常信息输出到字符串
- python使用管道获取其它进程的输出内容
- linux系统使用python获取内存使用信息脚本分享
- 飘逸的python - 使用traceback获取详细的异常信息
- 使用c#进行socket编程时,获取网卡的信息
- python获取天气信息写入原有的excel文档
- 使用python让nao检测naomark并输出信息
- 【python系列】使用 BeautifulSoup 获取 meta 信息
- python 学习笔记 12 -- 写一个脚本获取城市天气信息
- 使用Python获取CPU、内存和硬盘等windowns系统信息的2个例子
- 使用Python获取Linux系统的各种信息
- linux系统使用python获取内存使用信息脚本分享
- 树莓派使用python获取GY-85九轴模块信息
- Android网络编程之Web Service获取天气预报( 获取天气预报信息)
- 使用python获取CPU和内存信息的思路与实现(linux系统)
- 使用java获取未来7天天气信息,可用于android