1. 程式人生 > >《Dive into python3》:Chapter 6 閉包與生成器之生成器

《Dive into python3》:Chapter 6 閉包與生成器之生成器

在上一篇中我們使用了函式列表、匹配模式列表、匹配模式檔案實現了名詞單數形式轉換為複數形式,對於plural()函式,應當有一個通用的匹配規則檔案,我們將使用Generator (生成器)實現。

一、生成器的簡單示例:

二、使用生成器實現名詞單數轉換成複數形式

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 rules(rules_filename):
    with open(rules_filename,encoding='utf-8') as pattern_file:
        for line in pattern_file:
            pattern,search,replace = line.split(None,3)
            yield build_match_and_apply_functions(pattern,search,replace)

def plural(noun,rules_filename='plural4-rules.txt'):
    for matches_rule,apply_rule in rules(rules_filename):
        if matches_rule(noun):
            return apply_rule(noun)

    raise ValueError('no matching rule for {0}'.format(noun))

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

三、斐波那契生成器

四、複數規則生成器