我想寫一個接受一個字符串(句子)的函數,然後清理它並返回所有的字母,數字和一個henn。但是代碼似乎錯誤。請知道我在這裏做錯了什麼。Python清理一個句子中的單詞
例子:布雷克杜澤是d0噸
應返回:!布雷克杜澤是d0t
的Python:
def remove_unw2anted(str):
str = ''.join([c for c in str if c in 'ABCDEFGHIJKLNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890\''])
return str
def clean_sentence(s):
lst = [word for word in s.split()]
#print lst
for items in lst:
cleaned = remove_unw2anted(items)
return cleaned
s = 'Blake D\'souza is an !d!0t'
print clean_sentence(s)
您可以使用'string.letters + string.digits',而不是那個長字符串。 –
@Ashwini - 我還需要一些像hypen這樣倖免的符號,有沒有一個技巧呢? –
'allowed_chars = string.letters + string.digits +'-''就夠了。 –