【问题标题】:list of functions not work as intended in python 3函数列表在 python 3 中无法按预期工作
【发布时间】: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

【问题讨论】:

    标签: python list function


    【解决方案1】:

    您需要删除标记周围的's。像这样:

    rules.append(build_match_and_apply_functions(pattern.strip("'"), search.strip("'"), replace.strip("'")))
    

    或者像这样构建你的输入文件:

    [sxz]$            $   es
    [^aeioudgkprt]h$  $   es   
    [^aeiou]y$        y$  ies
    $                 $   s
    

    【讨论】:

      猜你喜欢
      • 2014-09-22
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      相关资源
      最近更新 更多