Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@wzpan
Created July 30, 2013 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wzpan/6112843 to your computer and use it in GitHub Desktop.
Save wzpan/6112843 to your computer and use it in GitHub Desktop.
Python - LazyRules
import re
class LazyRules:
rules_filename = 'rules.txt'
def __init__(self):
self.pattern_file = open(self.rules_filename, encoding='utf-8')
self.cache = []
def __iter__(self):
self.cache_index = 0
return self
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:
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)
return funcs
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 = LazyRules() # 实例化一个单一实例,打开模式文件但不读取
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment