...

/

A List Of Patterns

A List Of Patterns

We'll cover the following...

Defining separate named functions for each match and apply rule isn’t really necessary. You never call them directly; you add them to the rules sequence and call them through there. Furthermore, each function follows one of two patterns. All the match functions call re.search(), and all the apply functions call re.sub(). Let’s factor out the patterns so that defining new rules can be easier.

Press + to interact
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) #③

build_match_and_apply_functions() is a function that builds other functions dynamically. It takes pattern, search and replace, then defines a matches_rule() function which calls re.search() with the pattern that was passed to the build_match_and_apply_functions() function, and the word that was passed to the matches_rule() function you’re building. Whoa.

② Building the apply function works the same way. The apply function is a function that takes one parameter, and ...