在上一篇中我们使用了函数列表、匹配模式列表、匹配模式文件实现了名词单数形式转换为复数形式,对于plural()函数,应当有一个通用的匹配规则文件,我们将使用Generator (生成器)实现。
一、生成器的简单示例:
二、使用生成器实现名词单数转换成复数形式
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]
def rules(rules_filename):
with open(rules_filename,encoding='utf-8') as pattern_file:
for line in pattern_file:
pattern,search,replace = line.split(None,3)
yield build_match_and_apply_functions(pattern,search,replace)
def plural(noun,rules_filename='plural4-rules.txt'):
for matches_rule,apply_rule in rules(rules_filename):
if matches_rule(noun):
return apply_rule(noun)
raise ValueError('no matching rule for {0}'.format(noun))
if __name__ == '__main__':
import sys
if sys.argv[1:]:
print(plural(sys.argv[1]))
else:
print(__doc__)
三、斐波那契生成器
什么是斐波那契数列?
斐波拉契数列又称兔子数列、黄金分割数列,例;1,1,2,3,5,8,13...,规则是:假设F(1)=1,F(2) = 1,那么F(n) = F(n-1) + F(n-2)(n>=3,且n是正整数),了解了什么是斐波拉契数列,接下来实现斐波拉契生成器。
'''斐波拉契生成器'''
def fib(max):
a,b = 0,1
while a < max:
yield a
a,b = b,a+b
if __name__ == '__main__':
print(list(fib(1000)))
''将生成器传给列表,列表将遍历整个生成器,并返回一个存有所有值的列表''
============= RESTART: D:/wq/src/chapter6/fibonacci_generator.py =============
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
>>>