[英]Dive into Python Chapter 7: How do I use this iterator?
在第7章中,作者创建了一个迭代器,该迭代器构建了将单数英语名词转换为复数形式的规则:
class LazyRules:
rules_filename = 'plural5-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]
if self.pattern_file.closed:
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()
尽管本书对这段代码的每一部分都提供了非常清晰而透彻的解释,但并未解释如何使用它? 如何使用这些规则更改名词?
我试图将此添加到类中:
def build_match_and_apply_functions(self, 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(self, noun):
for matches_rule, apply_rule in self.__next__():
if matches_rule(noun):
return apply_rule(noun)
raise ValueError('no matching rule for {0}'.format(noun))
Upd:我更改了janos注释中添加的代码。 所以现在看起来像这样:
class LazyRules:
rules_filename = 'plural5-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]
if self.pattern_file.closed:
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()
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))
现在就可以使用!!! 谢谢janos !
但是,我还有一个问题:为什么在build_match_and_apply_functions()
函数中, matches_rule(word)
具有变量'word' ,而在the plural()
函数中, matches_rule(noun)
具有变量'noun' ,该变量不应命名为相同?
plural
不应是LazyRules
的方法,而应是独立的功能。 它应该发出rules
(这是自定义迭代器类LazyRules
的实例):
def plural(self, 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.