[英]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.