从 Python 列表项中删除标点符号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4371231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:28:04  来源:igfitidea点击:

Removing Punctuation From Python List Items

pythonlist

提问by giodamelio

I have a list like

我有一个像

['hello', '...', 'h3.a', 'ds4,']

this should turn into

这应该变成

['hello', 'h3a', 'ds4']

and i want to remove only the punctuation leaving the letters and numbers intact. Punctuation is anything in the string.punctuationconstant. I know that this is gunna be simple but im kinda noobie at python so...

我只想删除标点符号,而保留字母和数字。标点符号是string.punctuation常数中的任何东西。我知道这很简单,但我在 python 方面有点菜鸟,所以......

Thanks, giodamelio

谢谢,乔达梅利奥

采纳答案by Mark Byers

Assuming that your initial list is stored in a variable x, you can use this:

假设您的初始列表存储在变量 x 中,您可以使用:

>>> x = [''.join(c for c in s if c not in string.punctuation) for s in x]
>>> print(x)
['hello', '', 'h3a', 'ds4']

To remove the empty strings:

要删除空字符串:

>>> x = [s for s in x if s]
>>> print(x)
['hello', 'h3a', 'ds4']

回答by Rafe Kettler

To make a new list:

要创建新列表:

[re.sub(r'[^A-Za-z0-9]+', '', x) for x in list_of_strings]

回答by Ant

import string

print ''.join((x for x in st if x not in string.punctuation))

ps st is the string. for the list is the same...

ps st 是字符串。因为名单是一样的......

[''.join(x for x in par if x not in string.punctuation) for par in alist]

i think works well. look at string.punctuaction:

我认为效果很好。看看 string.punctuaction:

>>> print string.punctuation
!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~

回答by Josh Bleecher Snyder

Use string.translate:

使用 string.translate:

>>> import string
>>> test_case = ['hello', '...', 'h3.a', 'ds4,']
>>> [s.translate(None, string.punctuation) for s in test_case]
['hello', '', 'h3a', 'ds4']

For the documentation of translate, see http://docs.python.org/library/string.html

有关翻译的文档,请参阅http://docs.python.org/library/string.html

回答by florex

In python 3+ use this instead:

在 python 3+ 中改用这个:

import string
s = s.translate(str.maketrans('','',string.punctuation))