Python 使用translate和maketrans函数从列表中删除标点符号
需要从列表中删除标点符号,然后将其保存在同一列表中 代码:Python 使用translate和maketrans函数从列表中删除标点符号,python,punctuation,Python,Punctuation,需要从列表中删除标点符号,然后将其保存在同一列表中 代码: sentences = ["Hi! How are you doing?","Hope everything is fine.","Have an amazing day!"] type(list1) sentences = sentences.translate(str.maketrans('', '', string.punctuation)) 错误: AttributeError
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'
AttributeError回溯(最近一次调用)
在()
1句话=[“嗨!你好吗?”,“希望一切都好。”,“祝你今天过得愉快!”]
2类(列表1)
---->3个句子=句子.翻译(str.maketrans('','',string.标点符号))
AttributeError:“list”对象没有属性“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']
谢谢你,马克!这帮了大忙。