Guest User

Untitled

a guest
Jan 21st, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. from re import *
  2.  
  3. def pluralize(noun, funcs):
  4. for matches_rule, apply_rule in funcs:
  5. if matches_rule(noun):
  6. return apply_rule(noun)
  7. raise ValueError("no matching rule for {0}".format(noun))
  8.  
  9.  
  10. def build_match_and_apply_functions(pattern, search, replace):
  11. def matches_rule(word):
  12. return re.search(pattern, word)
  13. def apply_rule(word):
  14. return re.sub(search, replace, word)
  15. return (matches_rule, apply_rule)
  16.  
  17.  
  18. class LazyRules:
  19. rules_filename = 'rules.txt' #a class variable - shared across all instances of the LazyRules class
  20. def __init__(self):
  21. self.pattern_file = open(self.rules_filename, encoding="utf-8")
  22. self.cache=[]
  23. def __iter__(self):
  24. self.cache_index=0
  25. return self #returning self signals that this class defines a __next__ method
  26. def __next__(self):
  27. self.cache_index += 1
  28. if len(self.cache) >= self.cache_index:
  29. return self.cache[self.cache_index-1]
  30. if self.pattern_file.closed:
  31. raise StopIteration
  32. line = self.pattern_file.readline()
  33. 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")
  34. self.pattern_file.close()
  35. raise StopIteration
  36. pattern,search,replace= line.split(None,3)
  37. funcs = build_match_and_apply_functions(pattern,search,replace)
  38. self.cache.append(funcs) # before returning the match&apply functions, we save them in the list self.cache
  39. return funcs
  40.  
  41. [sxz]$ $ es
  42. [^aeioudgkprt]h$ $ es
  43. [^aeiou]y$ y$ ies
  44. $ $ s
  45.  
  46. import pluralizer
  47. funcs = pluralizer.LazyRules()
  48. p = pluralizer.pluralize("baby", funcs)
  49.  
  50. NameError: name 're' is not defined
Add Comment
Please, Sign In to add comment