`

python 之 求英语单词复数的 一种实现方式

阅读更多
#!/usr/bin/evn python

import re;

def GetMatchAndApplyFuncs(strPattern, strSearch, strReplace):
    def MatchRule(strWord):
        return re.search(strPattern, strWord);
    
    def ApplyRule(strWord):
        return re.sub(strSearch, strReplace, strWord);
    
    return (MatchRule, ApplyRule);

g_tlPattern = (
    ('[sxz]$',           '$',  'es'),
    ('[^aeioudgkprt]h$', '$',  'es'),
    ('(qu|[^aeiou])y$',  'y$', 'ies'),
    ('$',                '$',  's')  
);

g_lsRules = [GetMatchAndApplyFuncs(strPattern, strSearch, strReplace) for (strPattern, strSearch, strReplace) in g_tlPattern];

def GetPlural(strWord):
    if not strWord:
        return "";
    
    for fnMatch, fnApply in g_lsRules:
        if fnMatch(strWord):
            return fnApply(strWord);
        
if "__main__" == __name__:
    strVal = "exhs";
    strPlural = GetPlural(strVal);
    print("%s plural ==> %s" %(strVal, strPlural));
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics