【发布时间】:2017-09-11 03:42:02
【问题描述】:
这是来自 Dive into Python: 它有两个部分: 第一部分:名为plural-rules.txt的文件:
'[sxz]$' '$' 'es'
'[^aeioudgkprt]h$' '$' 'es'
'[^aeiou]y$' 'y$' 'ies'
'$' '$' 's'
第二个是a.py:
def build_match_and_apply_functions(pattern, search, replace):
def matches_rule(word):
return re.search(pattern, word)
def apply_rule(word):
return re.sub(search, replace, word)
return (matches_rule, apply_rule)
rules=[]
with open('plural-rules.txt') as pattern_file:
for line in pattern_file:
pattern,search, replace=line.split(None, 3)
#print(pattern, search, replace)
#print(line,end='')
rules.append(build_match_and_apply_functions(pattern, search, replace))
def plural(word):
for matches, plurals in rules:
if matches(word):
return plurals(word)
print(rules[2][1]('shobby')) ---------------------1
print("shobby's plural is", plural('shobby'))----------------------2
1 打印输出:shobby 2 打印出来:shobby 的复数形式是 None
【问题讨论】: