需要從列表中刪除標點符號,然后將其保存在同一列表中法典:sentences = ["Hi! How are you doing?","Hope everything is fine.","Have an amazing day!"]type(list1)sentences = sentences.translate(str.maketrans('', '', string.punctuation))錯誤:AttributeError Traceback (most recent call last)<ipython-input-4-7b3b0cbf9c58> in <module>() 1 sentences = ["Hi! How are you doing?","Hope everything is fine.","Have an amazing day!"] 2 type(list1)----> 3 sentences = sentences.translate(str.maketrans('', '', string.punctuation))AttributeError: 'list' object has no attribute 'translate'
1 回答

HUH函數
TA貢獻1836條經驗 獲得超4個贊
錯誤告訴你真相。列表沒有屬性,字符串有屬性。您需要對列表中的字符串(而不是列表本身)調用此函數。列表理解對此有好處。在這里,您可以調用列表中的每個字符串:translatetranslate()
import string
sentences = ["Hi! How are you doing?","Hope everything is fine.","Have an amazing day!"]
trans = str.maketrans('', '', string.punctuation)
[s.translate(trans) for s in sentences]
# ['Hi How are you doing', 'Hope everything is fine', 'Have an amazing day']
添加回答
舉報
0/150
提交
取消