我正在阅读 Mark Pilgrim 的 Dive into Python 3。他给出了名词复数形式的“必杀技”代码。我的问题是:第 30 行和第 31 行的代码是否必要?没有它们,该程序似乎运行良好。添加它们有什么好处?谢谢
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 plural(noun):
for matches_rule, apply_rule in rules:
if matches_rule(noun):
return apply_rule(noun)
raise ValueError('no matching rule for {0}'.format(noun))
class LazyRules:
rules_filename = 'plural6-rules.txt'
def __init__(self):
self.pattern_file = open(self.rules_filename, encoding='utf-8')
self.cache = []
def __iter__(self):
self.cache_index = 0
return self
def __next__(self):
self.cache_index += 1
if len(self.cache) >= self.cache_index:
return self.cache[self.cache_index - 1]
##Line 30: if self.pattern_file.closed:
##Line 31: raise StopIteration
line = self.pattern_file.readline()
if not line:
self.pattern_file.close()
raise StopIteration
pattern, search, replace = line.split(None, 3)
funcs = build_match_and_apply_functions(pattern, search, replace)
self.cache.append(funcs)
return funcs
rules = LazyRules()
nouns=['fox', 'horse', 'cheetah','ad', 'quay', 'vacancy']
for noun in nouns:
print (noun)
print(plural(noun)+'\n')
## plural6-rules.txt:
##[sxz]$ $ es
##[^aeioudgkprt]h$ $ es
##[^aeiou]y$ y$ ies
##$ $ s