使用 translate 和 maketrans 函数从列表中删除标点符号
Remove punctuation mark from the list using translate and maketrans function
需要从列表中删除标点符号,然后将其保存在同一个列表中
代码:
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
属性——字符串有。您需要在列表中的字符串而不是列表本身上调用它。列表理解对此有好处。在这里,您可以对列表中的每个字符串调用 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']
需要从列表中删除标点符号,然后将其保存在同一个列表中
代码:
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
属性——字符串有。您需要在列表中的字符串而不是列表本身上调用它。列表理解对此有好处。在这里,您可以对列表中的每个字符串调用 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']