python-使用一行代码删除句子列表中的标点符号

python-使用一行代码删除句子列表中的标点符号,python,string,Python,String,所以我有一个句子列表,我想删除每个句子的标点符号。我可以通过以下方式删除它: textList = ['This is bad.', 'You, me, him are going'] from string import punctuation for text in textList: for p in punctuation: text = text.replace(p,'') print(text) 但是我想修改列表内容并只做一行。大概是这样的: #

所以我有一个句子列表,我想删除每个句子的标点符号。我可以通过以下方式删除它:

textList = ['This is bad.', 'You, me, him are going']

from string import punctuation

for text in textList:
    for p in punctuation:
        text = text.replace(p,'')
    print(text)
但是我想修改列表内容并只做一行。大概是这样的:

# obviously this does not work
textList = [(text.replace(p,'') for p in punctuation) for text in textList]
res = [s.translate(str.maketrans('', '', string.punctuation)) for s in textList]

正确的方法是什么?

我认为你试图用一行字来解决这个问题的事实表明这更像是一个谜,所以我不会用完整的答案来回答

所以,有很多方法可以做到这一点。例如,您可以构建一个正则表达式,将所有标点一次性替换为零

但是,如果我们继续使用您的最后一行代码,我认为
reduce()
是您正在寻找的python内置版本

在Python 2中,您可以使用如下所示:

res = [s.translate(None, string.punctuation) for s in textList]
输出:

>>> textList = ['This is bad.', 'You, me, him are going']
>>> res = [s.translate(None, string.punctuation) for s in textList]
>>> res
['This is bad', 'You me him are going']
在Python 3中,可以这样使用:

# obviously this does not work
textList = [(text.replace(p,'') for p in punctuation) for text in textList]
res = [s.translate(str.maketrans('', '', string.punctuation)) for s in textList]
注意:使用您的方法,您可以:

res = []

for text in textList:
    new_text = ''.join(c for c in text if c not in string.punctuation)
    res.append(new_text)
一行:

res = [''.join(c for c in text if c not in string.punctuation) for text in textList]

为什么要在一行中完成呢?更干净的代码,我需要将它括在括号中,以形成一个列表。否则,我每次都必须执行list.append(),我不认为将嵌套循环的“逻辑”压缩到一行是“更干净的代码”。Python的口头禅是明确是一件好事,它实际上不是一个谜。我想做一行,但我想不出正确的语法来做。我只是想将标点符号:text中的p转换为
。将(p,”)
替换为1行,我可以用括号括起来形成一个列表。或者使用map:
textList=map(lambda x:x.translate(无,字符串.标点符号),textList)
@AshishRanjan列表理解比map更像python:)我得到了这个错误:
TypeError:translate()只接受一个参数(给定2个)
@ettanany是的,这就是为什么没有将其作为答案发布,只是建议了一个替代方案。此外,理解速度也会比使用lambdaneverment映射更快,请记住我之前的错误。我不得不在Python3中这样做
res=[s.translate(str.maketrans(“”,,,string.标点符号))表示文本列表中的s]