Python - 使用一行代码从句子列表中去除标点符号

3

我有一个句子列表,想要将每个句子中的标点符号移除。可以按照以下方式进行移除:

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]

什么是正确的做法?

为什么你必须要在一行中完成它? - cdarke
更简洁的代码,我需要将它括起来变成一个列表。否则每次都要使用list.append()。 - addicted
我认为将“逻辑上”是嵌套循环的东西挤入一行并不是“更干净的代码”。Python 的口号是显式优于隐式。 - Marcus Müller
2个回答

6
在Python 2中,您可以像下面这样使用str.translate()
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中,您可以像这样使用str.maketrans()
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]

或者使用map函数:textList = map(lambda x: x.translate(None, string.punctuation), textList) - Ashish Ranjan
@AshishRanjan 列表推导式比 map 更符合 Python 风格 :) - ettanany
我遇到了这个错误:TypeError: translate()接收到2个参数,但需要恰好1个参数 - addicted
@ettanany 你有什么想法,为什么我们不能在列表括号内使用text.replace(p,'')来替换标点符号? - addicted
@addicted,你遇到的问题之一是结果列表包含了生成器表达式,请查看编辑后的解决方案,使用你的方法可以解决这个问题。 - ettanany
显示剩余3条评论

0

我认为你试图用一行代码解决这个问题的事实表明这更像是一个谜题,所以我不会给出完整的解决方案。

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

但是,如果我们要坚持你最后一行代码的想法,我认为reduce()是你要寻找的Python内置函数!


这实际上不是一个谜语。我想要做一个一行代码,但我无法找出正确的语法来完成它。我只想将 from p in punctuation: text.replace(p,'') 转换为一个可以用括号括起来成为列表的一行代码。 - addicted

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接