以lambda形式优化结构 分类: python 小练习 divide into python python基础学习 2013-12-30 21:07 279人阅读 评论(0) 收藏

#coding:utf-8
import re
'''
以lambda函数形式将这些函数的内容直接嵌入rules列表本身
'''
rules=\
(
(lambda word:re.search('[sxz]$',word),
lambda word:re.sub('$','es',word)),

(lambda word:re.search('[^aeioudgkprt]h$',word),
lambda word:re.sub('$','es',word)),

(lambda word:re.search('[^aeiou]y$',word),
lambda word:re.sub('y$','ies',word)),

(lambda word:re.search('$',word),
lambda word:re.sub('$','s',word))

)

def plural(noun):
    for matchesRule,applyRule in rules:
        if matchesRule(noun):
            return applyRule(noun)
if __name__ == '__main__':
    main()


进一步优化:

#coding:utf-8
import re
def buildMatchAndApllyFunctions((pattern,search,replace)):#参数是一个元组
    matchFunction=lambda word:re.search(pattern,word)
    applFunction=lambda word:re.sub(search,replace,word)
    return matchFunction,applFunction

patterns=\
(
#注意此处使用的是包括三个元素的元组
('[szx]$','$','es'),
('[^aeioudgkprt]h$','$','es'),
('(qu|[^aeiou])y$','y$','ies'),
('$','$','s')
)

rules=map(buildMatchAndApllyFunctions,patterns)

def plural(noun):
    for matchesRule,applyRule in rules:
        if matchesRule(noun):
            return applyRule(noun)

if __name__ == '__main__':
    plural(noun)




版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2013-12-30 21:07  前行者2011  阅读(180)  评论(0编辑  收藏  举报