2017-03-05 73 views
0

我已經寫下面的代碼來發現服用輸入忽略一些特殊字符在Python字的長度長度在一個列表中的單詞,而不計數標點符號

def word_length_list(text): 
    special_characters = ["'","?"] 
    for string in special_characters: 
     clean_text = text.replace(string, "") 
    count_list = [len(i) for i in clean_text.split()] 
    print count_list 

輸出僅接受第一特殊字符,而忽略休息。 請在這裏提示我的代碼有什麼問題。

回答

1

既然你做多內容替換,則需要更新相同的變量(clean_text),每個替換:

def word_length_list(text): 
    special_characters = ["'","?"] 
    clean_text = text 
    for string in special_characters: 
     clean_text = clean_text.replace(string, "") 
    count_list = [len(i) for i in clean_text.split()] 
    print count_list 

這樣多的特殊字符將被刪除:

>>> word_length_list("abc def ' ghi ? lmo") 
[3, 3, 3, 3] 
+0

謝謝噸Bejado – Bala

相關問題