繁体   English   中英

Dive Into Python 3中的迭代器示例

[英]Iterator example from Dive Into Python 3

我正在从http://www.diveintopython3.net/学习Python作为我的第一语言。 在第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__)

我的问题是:在满足if条件后,“ for规则中的match_rule,apply_rule:”规则中的循环如何知道何时退出? 没有针对该条件的StopIteration命令。 我希望for循环继续进行直到完全迭代rules.cache。

感谢您的帮助!

return语句在该点结束函数,将值返回给调用方。 这几乎可以在任何情况下使用(如果您尝试使用try..except..else..finally结构,即使return语句也不会阻止finally块的执行)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM