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

17

I have a list like

['hello', '...', 'h3.a', 'ds4,']
这应该变成 <\p>。
['hello', 'h3a', 'ds4']

我想只删除标点符号,保留字母和数字。 标点符号是指在string.punctuation常量中的任何字符。 我知道这很简单,但我在Python方面有些新手...

谢谢, giodamelio

6个回答

28

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

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

去除空字符串:

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

9

使用 string.translate:

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

有关translate的文档,请参见http://docs.python.org/library/string.html


2
+1 因为我喜欢它,而且不知道翻译可以在不使用奇怪的翻译表的情况下删除字符。 - Jochen Ritzel

3

在Python 3+中,请改用以下内容:

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

2
import string

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

PS ST是一种字符串。对于列表也是一样的...

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

我认为这很好用。看一下string.punctuaction:
>>> print string.punctuation
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~

1
创建新列表的方法如下所示:
[re.sub(r'[^A-Za-z0-9]+', '', x) for x in list_of_strings]

2
那不会对列表做任何事情。 - nmichaels

0

请注意,string.punctuation适用于英语,但可能不适用于其他具有其他标点符号的语言。

您可以将它们添加到LIST_OF_LANGUAGE_SPECIFIC_PUNCTUATION列表中,然后将其连接到string.punctuation以获得更完整的标点符号集。

punctuation =  string.punctuation + [LIST_OF_LANGUAGE_SPECIFIC_PUNCTUATION]

你应该使用简单的注释来编写,因为这不是完整的答案。 - Malo

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