2 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超8個贊
那是因?yàn)槟鷱牡谝恍械姆椒ǚ祷?,在return text.replace(" ",''). 將其更改為text = text.replace(" ", ""),它應(yīng)該可以正常工作。
此外,縮進(jìn)可能在您的帖子中搞砸了,可能是在復(fù)制粘貼期間。
完整的方法片段:
def remove_punctuation(text):
text = text.replace(" ",'')
exclude = set(string.punctuation)
return ''.join(ch for ch in text if ch not in exclude)

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個贊
您可以使用str以下方法刪除不需要的字符:
import string
tr = ''.maketrans('','',' '+string.punctuation)
def remove_punctuation(text):
return text.translate(tr)
txt = 'Point.Space Question?'
output = remove_punctuation(txt)
print(output)
輸出:
PointSpaceQuestion
maketrans創(chuàng)建替換表,它接受 3 str-s:第一個和第二個必須等長,第一個的第 n 個字符將替換為第二個的第 n 個字符,第三個str是要刪除的字符。您只需要刪除(而不是替換)字符,因此前兩個參數(shù)是空str的。
添加回答
舉報