2015-11-01 105 views
0
def wordlist (l: list) -> list: 
    '''Returns a wordlist without white spaces and punctuation''' 
    result = [] 
    table = str.maketrans('!()-[]:;"?.,', '   ') 
    for x in l: 
     n = x.translate(table) 
     n = x.strip() 
     n = x.split() 
     if n != []: 
      result.extend(n) 
    return result 

的功能应该是这样的工作:删除空格和标点符号从列表

print(wordlist([' Testing', '????', 'function!!'])) 

应该产生:

['Testing', 'function'] 

,但我的代码有上述收益率:

['Testing', '??', 'function!!'] 

所以我假设我正在做一些事情正确地与代码去除标点符号 - 我应该在哪里修复它?任何其他建议,以简化代码也将不胜感激(因为我觉得它有点冗长)。

+0

你确定你想测试'N = []'而不是'N = “”' –

+0

我到底拿了出来!因为它没有任何意义的功能 –

回答

1

您的意思是连锁translate(table)strip()split()来电?

然后

n = x.translate(table) 
n = x.strip() 
n = x.split() 

应该

n = x.translate(table) 
n = n.strip() # change x to n 
n = n.split() # same here 

n = x.translate(table).split() 

无需中间strip()

至于进一步的简化,你不必检查n空虚,它看起来像一个不成熟的优化对我说:

if n != []: # you can remove this line 
    result.extend(n) 

结果:

def wordlist (l: list) -> list: 
    '''Returns a wordlist without white spaces and punctuation''' 
    result = [] 
    table = str.maketrans('!()-[]:;"?.,', '   ') 
    for x in l: 
     result.extend(x.translate(table).split()) 
    return result 

你甚至可以用列表理解替换该循环。

+0

有没有办法删除所有标点符号?我不确定标点符号是什么,所以我想到的所有内容都在那里,但是Python有一个内置的标点符号列表,可以用于翻译吗? –

+0

@RamonHallan是的,它确实是''import string'并使用'str.maketrans(string.punctuation,''* len(string.punctuation))' – vaultah

0

可能很多清洁剂只使用re.sub这里:

import re 
clean = re.compile(r'[!()\-\[\]:;"?.,\s]') 

words = [' Testing', '????', 'function!!'] 
result = list(filter(bool, (clean.sub('', w) for w in words))) 
print result 
# ['Testing', 'function'] 
相关问题