import re
'''method1============================================================'''
def matchx(noun):
return re.search('[szx]$', noun)
def matchy(noun):
return re.search('[yam]$', noun)
def applyx(noun):
return re.sub('$','es', noun)
def applyy(noun):
return re.sub('$', 's', noun)
rules={(matchx,applyx),(matchy,applyy)}
def check(noun):
for mm, app in rules:
if mm(noun):
return app(noun)
'''method 2=============================================================
closures: use external parameter in dynamic funtions like "word" bellow
'''
def application_funct(pattern, search , replace):
def matchf(word):
return re.search(pattern, word)
def applyf(word):
return re.sub(search, replace, word)
return (matchf, applyf)
data1=[('[szx]$', '$', 'es'), ('[yam]$', '$', 's')]
rules2=[application_funct(pattern11, search11 , replace11) for (pattern11, search11, replace11) in data1]
def check2(word):
for mm,app in rules2:
if mm(word):
return app(word)
'''method 3=================================================================================='''
rules3=[]
with open('plural_util_b.txt', encoding='utf-8') as patternfile:
for line in patternfile:
pattern, search, replace = line.split(None,3)
rules3.append(application_funct(pattern, search, replace))
def check3(word):
for mm, app in rules3:
if mm(word):
return app(word)
def make_counter(x):
print('enter make_counter')
while True:
yield x
print('incresing x')
x=x+1
def make_counter2(x):
print('enter make_counter2')
yield x
print('add x1')
x=x+1
yield x
print('add x2')
x=x+1
if __name__ == '__main__':
print(check('box'))
print(check('supply'))
print(check2('box'))
print(check2('supply'))
print(check3('box'))
print(check3('supply'))
counter1 = make_counter(2)
print(counter1)
print(next(counter1))
print(next(counter1))
counter2 = make_counter2(1)
print(next(counter2))
print(next(counter2))
'''
yield: stop function
next: start from last yield
generator: make_counters will return a set of value , the value is behind yield
'''
Python---generator
最新推荐文章于 2024-08-04 13:04:28 发布