来自Dive Into Python 3的迭代器示例

时间:2016-01-11 02:56:37

标签: python python-3.x iterator

我从http://www.diveintopython3.net/学习Python作为我的第一语言。在Chp 7,http://www.diveintopython3.net/iterators.html,有一个如何使用迭代器的例子。

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]

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]

        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 plural(noun):
    for matches_rule, apply_rule in rules:
        if matches_rule(noun):
            return apply_rule(noun)

if __name__ == '__main__':
    import sys
    if sys.argv[1:]:
        print(plural(sys.argv[1]))
    else:
        print(__doc__)

我的问题是:如何在规则中匹配match_rule,apply_rule:'复数(名词)函数中的循环知道何时在满足if条件后退出?该条件没有StopIteration命令。我希望for循环能够继续,直到完全迭代rules.cache。

谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

return语句在该点结束函数,向调用者返回一个值。几乎在任何情况下都可以依赖它(如果你有try..except..else..finally结构,即使return语句也不能阻止执行finally块。