2015-11-01 69 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']