【问题标题】:Remove nonalphabet letters using a function, returning incorrect使用函数删除非字母字母,返回不正确
【发布时间】:2021-12-02 01:56:17
【问题描述】:

对于一个作业,我正在创建函数 remove_extraneous,旨在接收任何字符串并返回仅包含字母表中字母的字符串。到目前为止,这是我的尝试:

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

def remove_extraneous(text):
    '''
    Description: 
        
    Examples:
    >>> remove_extraneous('test !')
    
    >>> remove_extraneous('code??')
    '''
    
    return ([text.replace(i, "") for i in text if i not in alphabet])

我的例子返回:

Examples:
    >>> remove_extraneous('test !')
    ['test!', 'test ']
    >>> remove_extraneous('code??')
    ['code', 'code']

到目前为止,这很好,因为它有点工作,但并不完全。它应该返回:

Examples:
    >>> remove_extraneous('test !')
    'test'
    >>> remove_extraneous('code??')
    'code'

另外,我的老师的例子说这个例子应该返回这个:

>>> remove_extraneous('boo!\n')
    'boo'

但是当我尝试它时,我的返回以下错误:

raise ValueError('line %r of the docstring for %s has '

ValueError: line 10 of the docstring for __main__.remove_extraneous has inconsistent leading whitespace: "')"

换行符真的让我很困惑,所以请耐心等待... 但总的来说,我应该在我的代码中进行哪些更改才能返回正确的字符串值?

【问题讨论】:

  • 试着反过来想,即只保留字母表中的字符
  • 你返回的是一个列表理解,所以它必须返回一个列表,而不是单个字符串。
  • 你最后得到的错误似乎不是你发布的代码。
  • @Barmar 我的猜测是 OP 在文档字符串中添加了remove_extraneous('boo!\n')

标签: python string function replace list-comprehension


【解决方案1】:

您可以大大简化这一点。确保返回str,而不是list

from string import ascii_lowercase

alphabet = set(ascii_lowercase)

def remove_extraneous(text):
    return "".join(c for c in text if c in alphabet)

>>> remove_extraneous('test !')
'test'
>>> remove_extraneous('code??')
'code'
>>> remove_extraneous('boo!\n')
'boo'

一些文档:

【讨论】:

  • 感谢您的帮助!不过,我仍然感到困惑,这对我来说适用于前两个示例,但是当我包含 \n (最后一个示例)时仍然返回错误
【解决方案2】:

这就是您的代码不起作用的原因。

当你这样做时:

[text.replace(i, "") for i in text if i not in alphabet]

如果字母不在字母表中,则生成一个列表,其中每个字母都有一个项目。

对于'abc',您将一无所有,对于'abc!',您将拥有['abc'],因为您有一个无效字符,对于'abc!!!!!!!!',您将获得与感叹号一样多的项目。

第二个想法。使用replace 并在字符上循环是效率不高,因为您将解析完整字符串的次数与字符数一样多,因此粗略地您将解析它的长度的平方。这意味着你的代码会很快变得非常慢。

正确的做法是对字符逐一检查,如果在白名单中就保留:

[char for char in text if char in alphabet]

然后你得到一个列表,你需要通过加入字符将其转换回字符串:

''.join(char for char in text if char in alphabet)

【讨论】:

    【解决方案3】:

    我建议使用re 正则表达式模块:

    import re
    
    non_letters = re.compile('[^A-Za-z]')
    
    def remove_extraneous(text):
        return non_letters.sub('', text)
    

    【讨论】:

      猜你喜欢
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多