Python---generator

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
	'''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值