模式匹配列表 闭包

xiaoxiao2021-02-28  43

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) patterns = \ ( ('[sxz]$', '$', 'es'), ('[^aeioudgkprt]h$', '$', 'es'), ('(qu|[^aeiou])y$', 'y$', 'ies'), ('$', '$', 's') ) rules = [build_match_and_apply_functions(pattern, search,replace) for (pattern, search, replace) in patterns] def plural(noun): for matches_rule, apply_rule in rules: if matches_rule(noun): return apply_rule(noun)
转载请注明原文地址: https://www.6miu.com/read-2623349.html

最新回复(0)