>>> 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. Atitit onvif 协议截图 getSnapshotUri 使用java

    Atitit onvif 协议截图 getSnapshotUri 使用java 1.1. ONVIF Device Test Tool1 1.2. 源码2 1.3. 直接浏览器访问http://192 ...

  2. ASP.NET 访问共享文件夹

    配置代码: var dataProtection = new Microsoft.AspNet.DataProtection.DataProtectionProvider(new DirectoryI ...

  3. 【Python五篇慢慢弹】数据结构看python

    数据结构看python 作者:白宁超 2016年10月9日14:04:47 摘要:继<快速上手学python>一文之后,笔者又将python官方文档认真学习下.官方给出的pythondoc ...

  4. 两种方式实现java生成Excel

    Web应用中难免会遇到需要将数据导出并生成excel文件的需求.同样,对于本博客中的总结,也是建立在为了完成这样的一个需求,才开始去了解其实现形式,并且顺利完成需求的开发,先将实现过程总结于此.本博文 ...

  5. Unity 3D json嵌套使用以及多种类型匹配

    我们控制端要发送很多命令给终端设备,其中有速度,方向,开关门,开关灯....方法千万种,我只取一瓢.我还小,不知道其他人是怎么写的.我喜欢把有规律的东西放在一起写!为了我的强迫症! using Uni ...

  6. [C#] 多线程总结(结合进度条)

    线程生命周期(来源 w3cschool) 未启动状态:当线程实例被创建但 Start 方法未被调用时的状况. 就绪状态:当线程准备好运行并等待 CPU 周期时的状况. 不可运行状态: 已经调用 Sle ...

  7. js验证输入的是否是数字,小数保留几位小数

    1.验证方法 validationNumber(e, num)  e代表标签对象,num代表保留小数位数 function validationNumber(e, num) { -]+\.?[-]*$ ...

  8. Django模型类Meta元数据详解

    转自:https://my.oschina.net/liuyuantao/blog/751337 简介 使用内部的class Meta 定义模型的元数据,例如: from django.db impo ...

  9. enote笔记语言(2)

    why not(whyn't)                 为什么不(与“why”相对应,是它的反面)   how对策 how设计     key-memo                    ...

  10. spring源码:BeanPostProcessor(li)

    在spring管理Bean的初始化过程中,除了正常管理bean的实例化(初始化.参数注入等)外,还对外提供了丰富的对Bean操作的扩展.例如自定义初始化操作,自定义容器退出时Bean的销毁操作等等.这 ...