>>> 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. ASP.NET AntiXSS的作用

    XSS跨站脚本攻击        是指用户输入HTML编码对网站进行跨站攻击.            通过使用FCKeditor.FreeTextBox.Rich TextBox.Cute Edito ...

  2. ASP.NET MVC5+EF6+EasyUI 后台管理系统(38)-Easyui-accordion+tree漂亮的菜单导航

    系列目录 本节主要知识点是easyui 的手风琴加树结构做菜单导航 有园友抱怨原来菜单非常难看,但是基于原有树形无限级别的设计,没有办法只能已树形展示 先来看原来的效果 改变后的效果,当然我已经做好了 ...

  3. .NET Core采用的全新配置系统[1]: 读取配置数据

    提到“配置”二字,我想绝大部分.NET开发人员脑海中会立马浮现出两个特殊文件的身影,那就是我们再熟悉不过的app.config和web.config,多年以来我们已经习惯了将结构化的配置定义在这两个文 ...

  4. 代码的坏味道(13)——过多的注释(Comments)

    坏味道--过多的注释(Comments) 特征 注释本身并不是坏事.但是常常有这样的情况:一段代码中出现长长的注释,而它之所以存在,是因为代码很糟糕. 问题原因 注释的作者意识到自己的代码不直观或不明 ...

  5. Xamarin for Visual Studio V3.11.431 于 2015.4.3-2015.4.17 最新发布(Win & Mac)

    Beta Release: April 3 edited April 17 in Visual Studio Released versions: Windows Xamarin.VisualStud ...

  6. c#面向对象基础技能——学习笔记(三)基于OOP思想研究对象的【方法】

    实例方法:(解决问题的步骤)完成某功能的各种语句的组合 编写方法要考虑的内容: 1.通过项目需求,确定各方法的任务.功能: 2.方法的可访问性(默认是private):(字段private 属性int ...

  7. LINQ to SQL语句(8)之Concat/Union/Intersect/Except

    适用场景:对两个集合的处理,例如追加.合并.取相同项.相交项等等. Concat(连接) 说明:连接不同的集合,不会自动过滤相同项:延迟. 1.简单形式: var q = ( from c in db ...

  8. C# Linq排序

    今天在家看了一下linq,实践了一下书中代码,发现排序和查重的先后顺序太重要了. using System; using System.Collections.Generic; using Syste ...

  9. A2W、W2A、A2T、T2A的使用方法

    1.A2W和W2A 在<Window核心编程>,多字节和宽字节之间转换比较麻烦的,MultiByteToWideChar函数和WideCharToMultiByte函数有足够多的参数的意义 ...

  10. Atitit java集成内嵌浏览器与外嵌浏览器attilax总结

    Atitit java集成内嵌浏览器与外嵌浏览器attilax总结 HTML5将颠覆原生App世界.这听起来有点危言耸听,但若认真分析HTML5的发展史,你会发现,这个世界的发展趋势确实就是这样. 熟 ...