Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from re import *
- def pluralize(noun, funcs):
- for matches_rule, apply_rule in funcs:
- if matches_rule(noun):
- return apply_rule(noun)
- raise ValueError("no matching rule for {0}".format(noun))
- 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)
- class LazyRules:
- rules_filename = 'rules.txt' #a class variable - shared across all instances of the LazyRules class
- def __init__(self):
- self.pattern_file = open(self.rules_filename, encoding="utf-8")
- self.cache=[]
- def __iter__(self):
- self.cache_index=0
- return self #returning self signals that this class defines a __next__ method
- def __next__(self):
- self.cache_index += 1
- if len(self.cache) >= self.cache_index:
- return self.cache[self.cache_index-1]
- if self.pattern_file.closed:
- raise StopIteration
- line = self.pattern_file.readline()
- if not line: #if there's a line to read, it will not be an empty string (even if new row, it will be "n")
- self.pattern_file.close()
- raise StopIteration
- pattern,search,replace= line.split(None,3)
- funcs = build_match_and_apply_functions(pattern,search,replace)
- self.cache.append(funcs) # before returning the match&apply functions, we save them in the list self.cache
- return funcs
- [sxz]$ $ es
- [^aeioudgkprt]h$ $ es
- [^aeiou]y$ y$ ies
- $ $ s
- import pluralizer
- funcs = pluralizer.LazyRules()
- p = pluralizer.pluralize("baby", funcs)
- NameError: name 're' is not defined
Add Comment
Please, Sign In to add comment