【问题标题】:Python: issue with return statementPython:返回语句的问题
【发布时间】:2013-12-25 22:22:02
【问题描述】:

我目前正在学习使用 Dive Into Python 3 书(以及其他)在 Python 中编程。下面是本书第 5 章中的示例,展示了使用列表函数来复数单词。

import re

def match_sxz(noun):
    return re.search('[sxz]$', noun)

def apply_sxz(noun):
    return re.sub('$', 'es', noun)

def match_h(noun):
    return re.search('[^aeioudgkprt]h$', noun)

def apply_h(noun):
    return re.sub('$', 'es', noun)

def match_y(noun):
    return re.sub('y$', 'ies', noun)

def apply_y(noun):
    return re.sub('y$', 'ies', noun)

def match_default(noun):
    return True

def apply_default(noun):
    return noun + 's'

rules = ((match_sxz, apply_sxz),
         (match_h, apply_h),
         (match_y, apply_y),
         (match_default, apply_default)
         )

def plural(noun):
        for (matches_rule, apply_rule) in rules:
            if matches_rule(noun):
                return apply_rule(noun)

问题在于,当我尝试在 IDLE 中执行代码时,对于“学生”(具有简单复数形式的最后规则的单词)之类的单词,我没有得到正确的结果。符合其余规则的单词没有问题。

这是我从解释器中得到的:

>>> import plural
>>> plural.plural('copy')
'copies'
>>> plural.plural('hoax')
'hoaxes'
>>> plural.plural('beach')
'beaches'
>>> plural.plural('student')
'student'

真正奇怪的是,当我从解释器调用 apply_default() 函数时,工作就完成了!

>>> plural.apply_default('student')
'students'

【问题讨论】:

  • 您的来源中有错字:match_y 使用 re.sub 而不是 re.search
  • 您确定在 IDLE 中运行的是最新版本的代码吗?我的猜测是您在更改后没有重新加载代码

标签: python function tuples return


【解决方案1】:

您的match_y 函数错误:

def match_y(noun):
    # return re.sub('y$', 'ies', noun)   # NO!
    return re.search('y$', noun)

它总是会返回一个非空字符串,当作为布尔值测试时,它会被视为True;所以你应用了apply_y 规则,它什么也没做,因为你的单词上没有-y,并返回了结果(即原始单词)。

【讨论】:

  • 已修复。焕然一新的眼睛总是有帮助的。谢谢
【解决方案2】:

在您的代码中,match_y 将始终评估为 True。另外,看看 re.sub 的文档:

re.sub(pattern, repl, string, count=0, flags=0)

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement

repl.如果未找到该模式,则字符串原样返回。重复 可以是字符串或函数;如果是字符串,任何反斜杠 处理其中的逃逸。即 \n 转换为单个 换行符,\r 转换为回车,等等。 诸如 \j 之类的未知转义将被单独留下。反向引用,例如 \6, 替换为模式中第 6 组匹配的子字符串。

来源: http://docs.python.org/2/library/re.html

【讨论】:

    猜你喜欢
    • 2023-02-04
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2017-08-25
    相关资源
    最近更新 更多