3-2如何生成可迭代对象和迭代器对象

1、实现方法

使用第三方库requests,python的一个HTTP客户端库,跟urllib,urllib2类似,那为什么要用requests而不用urllib2呢?官方文档中是这样说明的:

python的标准库urllib2提供了大部分需要的HTTP功能,但是API太逆天了,一个简单的功能就需要一大堆代码。

这个库可用在py2和py3中

参考资料:

(1)官方中文文档:http://cn.python-requests.org/zh_CN/latest/

 

2)快速上手(官方中文文档) http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

 

3)PYTHON REQUESTS的安装与简单运用(张亚楠的博客):

http://www.zhidaow.com/post/python-requests-install-and-brief-introduction

4)Python-第三方库requests详解:http://blog.csdn.net/shanzhizi/article/details/50903748

 

(5)python requests用法总结:http://www.cnblogs.com/lilinwei340/p/6417689.html

 

用浏览器打开天气预报:http://wthrcdn.etouch.cn/weather_mini?city=余杭

可以看到一个json格式的字符串,也可以看成是python字典,这个字典很长只有一行,下面是自己缩进之后的字符串

{
    "data":
    {
        "yesterday":
            {
                "date":"27日星期三",
                "high":"高温 29℃",
                "fx":"北风",
                "low":"低温 20℃",
                "fl":"<![CDATA[3-4级]]>",
                "type":"阵雨"
            },
        "city":"余杭",
        "forecast":
            [
                {
                    "date":"28日星期四",
                    "high":"高温 20℃",
                    "fengli":"<![CDATA[<3级]]>",
                    "low":"低温 16℃",
                    "fengxiang":"北风",
                    "type":"阵雨"
                },
                {
                    "date":"29日星期五",
                    "high":"高温 23℃",
                    "fengli":"<![CDATA[<3级]]>",
                    "low":"低温 20℃",
                    "fengxiang":"东北风",
                    "type":"阵雨"
                },
                {
                    "date":"30日星期六",
                    "high":"高温 28℃",
                    "fengli":"<![CDATA[<3级]]>",
                    "low":"低温 21℃",
                    "fengxiang":"东风",
                    "type":"阵雨"
                },
                {
                    "date":"1日星期天",
                    "high":"高温 31℃",
                    "fengli":"<![CDATA[3-4级]]>",
                    "low":"低温 23℃",
                    "fengxiang":"南风",
                    "type":"多云"
                },
                {
                    "date":"2日星期一",
                    "high":"高温 29℃",
                    "fengli":"<![CDATA[3-4级]]>",
                    "low":"低温 21℃",
                    "fengxiang":"北风",
                    "type":"多云"
                }
            ],
        "ganmao":"相对于今天将会出现大幅度降温,易发生感冒,注意增加衣服,加强自我防护避免感冒。",
        "wendu":"17"
    },
    "status":1000,
    "desc":"OK"    
}

一、简单示例,在py3中的代码:

#coding:utf8  #注py3要用  #coding=utf-8

import requests

def getWeather(city):
    r = requests.get(u"http://wthrcdn.etouch.cn/weather_mini?city="+city)
    data = r.json()['data']['forecast'][0]
    return '%s: %s, %s'%(city,data['low'],data['high'])

print(getWeather(u'杭州'))

输出:

杭州: 低温 16℃, 高温 21℃

二、实现可迭代对象和迭代器对象使用,实现复杂的示例

#collections模块下的Iterable可迭代对象和迭代器对象Iterator

#查看他们的抽象接口分别是next 和__iter__

>>> from collections import Iterable,Iterator
>>> Iterator.__abstractmethods__
frozenset(['next'])
>>> Iterable.__abstractmethods__
frozenset(['__iter__']) 

在py3中的代码为

#coding:utf8

import requests
from collections import Iterable,Iterator

class WeatherIterator(Iterator):  #定义一个可迭代天气的类,继承Iterable可迭代类
    def __init__(self,cities):  #构造函数,维护一个城市列表
        self.cities = cities
        self.index = 0          #可迭代的序号 初始代为0

    def getWeather(self,city):       #将获得的天气信息函数封装类类中
        r = requests.get(u"http://wthrcdn.etouch.cn/weather_mini?city="+city)
        data = r.json()['data']['forecast'][0]
        return '%s: %s, %s'%(city,data['low'],data['high'])
    def next(self):
        if self.index == len(self.cities):#当迭代到序号为列表长度,即为全迭代完,抛出异常
            raise StopIteration
        city = self.cities[self.index]  #获取当前列表序号的元素
        self.index += 1             #迭代一次,序号加1
        return self.getWeather(city)   

class WeatherIterable(Iterable):#定义一个天气的迭代器类,继承Iterator迭代器类
    def __init__(self,cities):    #构造函数,维护一个城市列表
        self.cities = cities
    def __iter__(self):
        return WeatherIterator(self.cities)
#print(getWeather(u'杭州'))
View Code

测试:

for x in WeatherIterable([u'北京',u'上海',u'广州',u'深圳',u'杭州']):

    print x

输出:

北京: 低温 11℃, 高温 22℃

上海: 低温 19℃, 高温 24℃

广州: 低温 26℃, 高温 36℃

深圳: 低温 28℃, 高温 34℃

杭州: 低温 16℃, 高温 21℃

过程:

(1)出现TypeError: object() takes no parameters 是因为构造函数__init__()名字不正确。

(2)类中的函数都要在第一个位置加self即始不使用,也必须加,与C++不同,C++中编译器自动加,python中必须手动加

(3)可迭代的接口是__iter__()在此函数中需返回迭代器对象。迭代器接口是next()

 

另一个天气预报网站:http://www.weather.com.cn

 

posted on 2018-04-13 11:04  石中玉smulngy  阅读(181)  评论(0)    收藏  举报

导航