[英]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.