【问题标题】:How to get my function to acknowledge a spelling mistake?如何让我的功能承认拼写错误?
【发布时间】:2021-12-31 15:25:59
【问题描述】:

我有这个功能:

def is_an_oak(name): 
    """
    Returns True is name starts with 'quercus'
    >>> is_an_oak('Fagus sylvatica')
    False
    >>> is_an_oak('Quercuss petraea')
    False
    >>> is_an_oak('Quercus petraea')
    True
    >>> is_an_oak('quercus petraea')
    True
    """

    return name.lower().startswith('quercus')

但我需要它将“Quercuss”和任何其他类似的拼写错误返回为 False,目前它仍在注册为 True。我知道这是因为 .startswith() 方法,但我不知道用什么替换它才能接受“Quercus”作为唯一正确的答案。

【问题讨论】:

    标签: python string function


    【解决方案1】:

    实际上,您的代码非常接近,但在正确单词后的多余字符中漏掉了一处。例如:如果你比较 'abc' 和 'abcd' - 你会期待什么? (使用startswith方法,会得到True!)看更正和其他版本比较:

    def is_an_oak(text):
        return text.lower().startswith( 'quercus ') # add space after the word so it can detect the extra "s" 
    
    def is_an_oak(text): 
        words = text.split()         # break text into words
        return words[0].lower() == 'quercus'  # first word
    

    运行一些测试:

    words = ['Quercuss petrea', 'Quercus petrea']
    
    for w in words:
        print(is_an_oak(w))
    
    # Outputs:
    # False
    # True
    

    【讨论】:

    • 我尝试了你的建议,但是当我这样做时 >>> is_an_oak("Quercuss petraea") 在 python 的命令行中它仍然注册为 true
    • 我不知道我做错了什么,但我已经尝试了你的两种方法,并且它们都仍然是真实的。我不知所措!
    • 有趣。您是否获得了新的 function 而没有运行您的 old 函数? - 你能启动一个new 终端吗?或者您想复制代码并在pythontutor.com 中作为新会话运行。
    • 好的,所以我已经意识到我的问题,当我运行时 ->>> is_an_oak("Quercuss petraea") 如果我使用“”标记,它会返回为真。但是我是否改为 ->>> is_an_oak('Quercuss petraea') 然后它返回为假。但是现在我有另一个问题。此函数是在物种名称的 csv 文件中搜索 Quercus 的较大脚本的一部分,现在完整的脚本不会运行在 csv 中查找任何 Quercus。
    • 嗨,@amelia_plshelp - 如果您还有其他问题,请为它打开一个新帖子?如果您觉得这对您有帮助,请立即接受? stackoverflow.com/help/someone-answers
    猜你喜欢
    • 2021-12-20
    • 2020-10-26
    • 2014-07-15
    • 1970-01-01
    • 2013-08-13
    • 2019-06-26
    • 2011-07-21
    • 2018-06-15
    • 2011-08-04
    相关资源
    最近更新 更多