需要从列表中删除标点符号,然后将其保存在同一列表中
代码:
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'
错误告诉您真相。列表没有translate
属性-字符串有。您需要在列表中的字符串上调用此函数,而不是列表本身。列表理解对此有好处:
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']