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

 


posted @ 2015-12-28 20:09  xfei.zhang  阅读(137)  评论(0编辑  收藏  举报