Skip to content

Instantly share code, notes, and snippets.

@RichardBronosky
Created November 25, 2011 06:43
Show Gist options
  • Select an option

  • Save RichardBronosky/1392950 to your computer and use it in GitHub Desktop.

Select an option

Save RichardBronosky/1392950 to your computer and use it in GitHub Desktop.
[sxz]$ $ es
[^aeioudgkprt]h$ $ es
[^aeiou]y$ y$ ies
$ $ s
#!/usr/bin/env python3
# plural2.py
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)
rules = []
'''
This block only populates the rules list above.
It does not do any work, it just prepares the logic for doing the work.
'''
with open('plural-rules.txt', encoding='ascii') as pattern_file:
for line in pattern_file:
pattern, search, replace = line.split(None, 3)
rules.append(build_match_and_apply_functions(pattern, search, replace))
'''
This is the method that does the work.
Defining it isn't enough though, you have to call it somewhere.
'''
def plural(noun):
for matches_rule, apply_rule in rules:
if matches_rule(noun):
return apply_rule(noun)
'''
Testing __name__ is important because you only want to do this if
this script was called directly on the command line.
If you were to import this py file as a library like so:
import plural
You would want it to provide a plural method for you to use. You
would not want it to look at sys.argv[1] which probably would not
exist and would raise an exception.
'''
if __name__ == '__main__':
import sys
if sys.argv[1:]:
print(plural(sys.argv[1]))
else:
print(__doc__)
$ python3 plural2.py city
cities
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment