>>> import re
>>> re.search('[abc]','mark')
<_sre.SRE_Match object; span=(1, 2), match='a'> >>> re.sub('[abc]','o','Mark')
'Mork'
>>> re.sub('[abc]','o', 'carp')
'oorp'
import re

def plural(noun):
if re.search('[sxz]$',noun):
return re.sub('$','es',noun)
elif re.search('[^aeioudgkprt]h$',noun):
return re.sub('$','es',noun)
elif re.search('[^aeiou]y$',noun):
return re.sub('y$','ies',noun)
else:
return noun+'s'

注:

[abc] --匹配a,b,c中的任何一个字符

[^abc] -- 匹配除了a,b,c的任何字符

>>> import re
>>> re.search('[^aeiou]y$','vancancy')
<_sre.SRE_Match object; span=(6, 8), match='cy'> >>> re.sub('y$','ies','vacancy')
'vacancies'
>>> re.sub('([^aeiou])y$',r'\1ies','vacancy')
'vacancies'

注:

\1-- 表示将第一个匹配到的分组放入该位置。 如果有超过一个分组,则可用\2, \3等等。

函数列表:

a. 在动态函数中使用外部参数值的技术称为闭合。

import re

def build_match_and_apply_functions(pattern,search,replace):
def matches_rule(word):
return re.search(pattern,word) def apply_rule(word):
return re.sub(search,replace,word) return (matches_rule,apply_rule)

b.

>>> patterns = (
('[sxz]$','$', 'es'),
('[aeioudgkprt]h$', '$', 'es'),
('(qu|[^aeiou])y$', 'y$','ies'),
('$', '$', 's')
) >>> rules = [build_match_and_apply_functions(pattern, search, replace) for (pattern, search, replace) in patterns] >>> rules
[(<function build_match_and_apply_functions.<locals>.matches_rule at 0x10384d510>, <function build_match_and_apply_functions.<locals>.apply_rule at 0x10384d598>), (<function build_match_and_apply_functions.<locals>.matches_rule at 0x10384d620>, <function build_match_and_apply_functions.<locals>.apply_rule at 0x10384d6a8>), (<function build_match_and_apply_functions.<locals>.matches_rule at 0x10384d730>, <function build_match_and_apply_functions.<locals>.apply_rule at 0x10384d7b8>), (<function build_match_and_apply_functions.<locals>.matches_rule at 0x10384d840>, <function build_match_and_apply_functions.<locals>.apply_rule at 0x10384d8c8>)]
>>>

c.匹配模式文件

import re

def build_match_and_apply_functions(pattern, search,replace):
def matches_rule(word):
return re.search(pattern,word) def apply_rule(word):
return re.sub(search,replace,word) return (matches_rule,apply_rule) rules = []
with open('plural4-rules.txt', encoding = 'utf-8') as pattern_file:
for line in pattern_file:
pattern,search,replace = line.split(None,3) rules.append(build_match_and_apply_functions(pattern,search,replace))

1) open():打开文件并返回一个文件对象。

2) 'with':创建了一个context:当with语句结束时,python自动关闭文件,即便是打开是发生意外。

3)split(None,3): None表示对任何空白字符(空格,制表等)进行分隔。3表示针对空白分隔三次,丢弃该行剩下的部分。

生成器:

>>> def make_counter(x):
print('entering make_counter')
while True:
yield x
print('incrementing x')
x=x+1 >>> counter = make_counter(2)
>>> counter
<generator object make_counter at 0x1038643f0>
>>> next(counter)
entering make_counter
2
>>> next(counter)
incrementing x
3
>>> next(counter)
incrementing x
4
>>> next(counter)
incrementing x
5
def fib(max):
a,b = 0, 1 while a < max :
yield a
a, b = b, a+b >>> for n in fib(100):
print(n,end=' ') 0 1 1 2 3 5 8 13 21 34 55 89
>>> list(fib(200))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144

1)将一个生成器传递给list()函数,它将遍历整个生成器并返回所有生成的数值。

Python学习笔记5-闭合与生成器的更多相关文章

  1. python学习笔记四 迭代器,生成器,装饰器(基础篇)

    迭代器 __iter__方法返回一个迭代器,它是具有__next__方法的对象.在调用__next__方法时,迭代器会返回它的下一个值,若__next__方法调用迭代器 没有值返回,就会引发一个Sto ...

  2. python学习笔记——列表生成式与生成器

    1.列表生成式(List Comprehensions) python中,列表生成式是用来创建列表的,相较于用循环实现更为简洁.举个例子,生成[1*1, 2*2, ... , 10*10],循环用三行 ...

  3. Python学习笔记010_迭代器_生成器

     迭代器 迭代就类似于循环,每次重复的过程被称为迭代的过程,每次迭代的结果将被用来作为下一次迭代的初始值,提供迭代方法的容器被称为迭代器. 常见的迭代器有 (列表.元祖.字典.字符串.文件 等),通常 ...

  4. Python学习笔记之生成器、迭代器和装饰器

    这篇文章主要介绍 Python 中几个常用的高级特性,用好这几个特性可以让自己的代码更加 Pythonnic 哦 1.生成器 什么是生成器呢?简单来说,在 Python 中一边循环一边计算的机制称为 ...

  5. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  6. OpenCV之Python学习笔记

    OpenCV之Python学习笔记 直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书< ...

  7. Python学习笔记基础篇——总览

    Python初识与简介[开篇] Python学习笔记——基础篇[第一周]——变量与赋值.用户交互.条件判断.循环控制.数据类型.文本操作 Python学习笔记——基础篇[第二周]——解释器.字符串.列 ...

  8. 【Python学习笔记之二】浅谈Python的yield用法

    在上篇[Python学习笔记之一]Python关键字及其总结中我提到了yield,本篇文章我将会重点说明yield的用法 在介绍yield前有必要先说明下Python中的迭代器(iterator)和生 ...

  9. Python学习笔记(十一)

    Python学习笔记(十一): 生成器,迭代器回顾 模块 作业-计算器 1. 生成器,迭代器回顾 1. 列表生成式:[x for x in range(10)] 2. 生成器 (generator o ...

随机推荐

  1. Entity Framework 6 Recipes 2nd Edition(13-9)译 -> 避免Include

    问题 你想不用Include()方法,立即加载一下相关的集合,并想通过EF的CodeFirst方式实现. 解决方案 假设你有一个如Figure 13-14所示的模型: Figure 13-14. A ...

  2. Atitit各种SDM 软件开发过程SDP sdm的ddd tdd bdd设计

    Atitit各种SDM 软件开发过程SDP sdm的ddd tdd bdd设计 1.1. software development methodology (also known as SDM 1 1 ...

  3. iOS APP 如何做才安全

    本来 写了一篇<iOS 如何做才安全--逆向工程 - Reveal.IDA.Hopper.https抓包 等>,发现文章有点杂,并且“iOS 如何做才安全”这部分写的越来越多,觉得 分出来 ...

  4. Golang 生成随机数

    package main import ( "fmt" "math/rand" "time" ) func main() { rand.Se ...

  5. 前端学PHP之PDO基础操作

    × 目录 [1]创建PDO [2]使用PDO [3]事务处理 前面的话 PDO(php data object)扩展类库为php访问数据库定义了轻量级的.一致性的接口,它提供了一个数据库访问抽象层,这 ...

  6. 计算机程序的思维逻辑 (44) - 剖析TreeSet

    41节介绍了HashSet,我们提到,HashSet有一个重要局限,元素之间没有特定的顺序,我们还提到,Set接口还有另一个重要的实现类TreeSet,它是有序的,与HashSet和HashMap的关 ...

  7. c 算牌器代码

    int main() { // 算牌器 ]; ; do { printf("请输入牌名: \n"); scanf("%2s",char_name); ; ]) ...

  8. 深入理解java中的ArrayList和LinkedList

    杂谈最基本数据结构--"线性表": 表结构是一种最基本的数据结构,最常见的实现是数组,几乎在每个程序每一种开发语言中都提供了数组这个顺序存储的线性表结构实现. 什么是线性表? 由0 ...

  9. ICSharpCode.SharpZipLib 压缩、解压文件 附源码

    http://www.icsharpcode.net/opensource/sharpziplib/ 有SharpZiplib的最新版本,本文使用的版本为0.86.0.518,支持Zip, GZip, ...

  10. C#开发微信门户及应用(6)--微信门户菜单的管理操作

    前面几篇继续了我自己对于C#开发微信门户及应用的技术探索和相关的经验总结,继续探索微信API并分享相关的技术,一方面是为了和大家对这方面进行互动沟通,另一方面也是专心做好微信应用的底层技术开发,把基础 ...