[Tutor] Not understanding this code example. Help, please.

Eduardo Vieira eduardo.susan at gmail.com
Sat Feb 13 05:49:15 CET 2010


Hello! I was reading the latest version of Mark Pilgrim's "Dive into
Python" and am confused with these example about the pluralization
rules. See http://diveintopython3.org/examples/plural3.py and
http://diveintopython3.org/generators.html#a-list-of-patterns
Here is part of the code:
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)

this example works on IDLE: print plural("baby")
My question is "baby" assigned to "word" in the inner function? It's a
little mind bending for me...

Thanks,

Eduardo


More information about the Tutor mailing list