From 83c4c0528c64e0fb6d21a1e9c7ac02090593170e Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Wed, 8 Jul 2009 18:17:52 -0400 Subject: [PATCH] added paragraph about fallback rule in #a-list-of-patterns --- generators.html | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/generators.html b/generators.html index 3fb0dc9..207a901 100644 --- a/generators.html +++ b/generators.html @@ -227,12 +227,13 @@ def build_match_and_apply_functions(pattern, search, replace): ('[sxz]$', '$', 'es'), ('[^aeioudgkprt]h$', '$', 'es'), ('(qu|[^aeiou])y$', 'y$', 'ies'), - ('$', '$', 's') + ('$', '$', 's') ) -rules = [build_match_and_apply_functions(pattern, search, replace) +rules = [build_match_and_apply_functions(pattern, search, replace) for (pattern, search, replace) in patterns]
    -
  1. Our pluralization rules are now defined as a tuple of tuples of strings (not functions). The first string in each group is the regular expression pattern that you would use in re.search() to see if this rule matches. The second and third strings in each group are the search and replace expressions you would use in re.sub() to actually apply the rule to turn a noun into its plural. +
  2. Our pluralization “rules” are now defined as a tuple of tuples of strings (not functions). The first string in each group is the regular expression pattern that you would use in re.search() to see if this rule matches. The second and third strings in each group are the search and replace expressions you would use in re.sub() to actually apply the rule to turn a noun into its plural. +
  3. There’s a slight change here, in the fallback rule. In the previous example, the match_default() function simply returned True, meaning that if none of the more specific rules matched, the code would simply add an s to the end of the given word. This example does something functionally equivalent. The final regular expression asks whether the word has an end ($ matches the end of a string). Of course, every string has an end, even an empty string, so this expression always matches. Thus, it serves the same purpose as the match_default() function that always returned True: it ensures that if no more specific rule matches, the code adds an s to the end of the given word.
  4. This line is magic. It takes the sequence of strings in patterns and turns them into a sequence of functions. How? By “mapping” the strings to the build_match_and_apply_functions() function. That is, it takes each triplet of strings and calls the build_match_and_apply_functions() function with those three strings as arguments. The build_match_and_apply_functions() function returns a tuple of two functions. This means that rules ends up being functionally equivalent to the previous example: a list of tuples, where each inner tuple is a pair of functions. The first function is the match function that calls re.search(), and the second function is the apply function that calls re.sub().