python cookbook学习笔记(1)

python cookbook学习笔记
连载中
回调会第4章查看迭代器的用法


反向迭代迭代函数reversed()

[In]a = [1, 2, 3]
In [88]: reversed(a)
Out[88]: 

4.13小节

os.walk的使用

os.walk(top, topdown=True, onerror=None, followlinks=False)
名词解释:

  • topdown : 自上而下
  • onerror : This can show error to continue with the walk, or raise the exception to abort the walk.
  • top : Each directory rooted at directory, yields 3-tuples, i.e., (dirpath, dirnames, filenames)
    例子1:
# !/usr/bin/python

import os
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        print(os.path.join(root, name))
    for name in dirs:
        print(os.path.join(root, name))

例子解析:
os.walk(".", topdown=False)返回一个迭代器,root是当前的目录,dirs与filename都是list类型。
编译后运行这个程序,会自底向上(buttom-to-up)遍历每一个目录,而如果我们把topdown的值改变成True时,也就是自顶向下(top-to-down)遍历整个目录。
例子二:

import os
import fnmatch
import gzip
import bz2
import re

def gen_find(filepat, top):
    '''
    Find all filenames in a directory tree that match a shell wildcard pattern(shell通配符模式)
    '''
    for path, dirlist, filelist in os.walk(top):
        for name in fnmatch.filter(filelist, filepat):
            yield os.path.join(path,name)

def gen_opener(filenames):
    '''
    Open a sequence of filenames one at a time producing a file object.
    The file is closed immediately when proceeding to the next iteration.
    '''
    for filename in filenames:
        if filename.endswith('.gz'):
            f = gzip.open(filename, 'rt')
        elif filename.endswith('.bz2'):
            f = bz2.open(filename, 'rt')
        else:
            f = open(filename, 'rt')
        yield f
        f.close()

def gen_concatenate(iterators):
    '''
    Chain a sequence of iterators together into a single sequence.
    '''
    for it in iterators:
        yield from it

def gen_grep(pattern, lines):
    '''
    Look for a regex(正则表达式) pattern in a sequence of lines
    '''
    pat = re.compile(pattern)
    for line in lines:
        if pat.search(line):
            yield line

例子解析:

  • gzip :模块,文件格式
  • bz2 :模块,文件格式
  • gen_find函数
  • fnmath : 这个模块的函数fnmatch.filter(filelist, filepat),第一个参数是字符串列表,第二个参数是文件模式(filepattern),是正则表达式也是字符串)string)。
    使用案例
>>> fnmatch.filter(['foo.py', 'bar.pyc'], '*.py')
['foo.py']
  • gen_opener函数
  • gzip.open(filename, 'rt') :打开以.gzip结尾的文件,默认的打开mode是‘rb’,在这里的‘rt’是text mode
  • bz2.open(filename, 'rt') : 与gzip同理
  • gen_concatenate函数
  • yield 和 yield from的区别 :我先举一个例子,好好感受一下
>>>a = gen_concatenate([[2,3,4],[3,4,5]])
>>>next(a)
2
>>>next(a)
3
>>>def concatenate2(iterators):
...:   for it in iterators:
...:       yield it
...:
>>>a = gen_concatenate2([[2,3,4],[3,4,5]])
>>>next(a)
[2,3,4]

在大多数的应用下yield from 按顺序yield 了左手边可迭代对象内的所有的东西,yield 简单的代理了右手边的可迭代对象。

  • gen_grep函数
  • pat是一个re.compile对象, 如果string中有pat的匹配项,那么pat.search(string)返回True否则返回False

总结

在上面这个例子中,你可能会写类似这样的语句 lines = itertools.chain(*files) , 使得 gen_opener() 生成器能被全部消费掉。


4.14小节

强大的扁平化处理嵌套序列

from collections import Iterable
#flatten 扁平化
def flatten(items, ignore_types=(str, bytes)):
    for x in items:
        if isinstance(x, Iterable) and not isinstance(x, ignore_types):
            yield from flatten(x)
        else:
            yield x

items = [1, 2, [3, 4, [5, 6], 7], 8]
# Produces 1 2 3 4 5 6 7 8
for x in flatten(items):
    print(x)

例子解释:

  • isinstance(obj, class) : class可以是元组也可以是单个的类
  • collection里的Iterable类是所有可迭代对象的父类
  • ignore_types(str, bytes) : 是为了避免把字符串和字节串视为可迭代对象

4.16小节

用迭代器取代while循环

CHUNKSIZE = 8912

def reader2(s):
    for chunk in iter(lambda: s.recv(CHUNKSIZE), b''):
        pass
        # process_data(data)
>>> import sys
>>> f = open('/etc/passwd')
>>> for chunk in iter(lambda: f.read(10), ''):
...     n = sys.stdout.write(chunk)
...
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false
root:*:0:0:System Administrator:/var/root:/bin/sh
daemon:*:1:1:System Services:/var/root:/usr/bin/false
_uucp:*:4:4:Unix to Unix Copy Protocol:/var/spool/uucp:/usr/sbin/uucico
...
>>>

例子解析:

  • iter(lambda: f.read(10), '') : 这一段代码本来可以是
def readers(s):
    while True:
        data = f.read(10)
        if data == '':
            break
        process_data(data)

这种写法复杂一些但是很容易理解。另外,iter()可以接受一个可调用的对象,第二个参数(''),是哨兵(结束)值;如果想从socket或者文件中按块读取,可以重复的调用read()或者recv()

  • sys.stdout.write(chunk) : 向标准输出输出chunk

这一章的学习,我们学会了迭代器以及生成器的使用,这是python中非常实用的也是比较高级的特性,有了生成器,我们可以巧妙地减少系统的开销,简单的编写功能强大的代码,并且结合一些其他的库,我们可以非常好的对数据进行高效的整理。

你可能感兴趣的:(python cookbook学习笔记(1))