簡體   English   中英

使用函數刪除非字母,返回不正確

[英]Remove nonalphabet letters using a function, returning incorrect

對於分配,我正在創建函數 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: "')"

換行符真的讓我感到困惑,所以請耐心等待...但總的來說,我應該在代碼中更改什么才能返回正確的字符串值?

你可以大大簡化這個。 確保返回一個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'

一些文檔:

這就是您的代碼不起作用的原因。

當你這樣做時:

[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)

我建議使用re regex 模塊:

import re

non_letters = re.compile('[^A-Za-z]')

def remove_extraneous(text):
    return non_letters.sub('', text)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM