I have a list like
['hello', '...', 'h3.a', 'ds4,']
这应该变成 <\p>。['hello', 'h3a', 'ds4']
我想只删除标点符号,保留字母和数字。
标点符号是指在string.punctuation
常量中的任何字符。
我知道这很简单,但我在Python方面有些新手...
谢谢, giodamelio
假设您的初始列表存储在变量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']
使用 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
在Python 3+中,请改用以下内容:
import string
s = s.translate(str.maketrans('','',string.punctuation))
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]
>>> print string.punctuation
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~
[re.sub(r'[^A-Za-z0-9]+', '', x) for x in list_of_strings]
请注意,string.punctuation适用于英语,但可能不适用于其他具有其他标点符号的语言。
您可以将它们添加到LIST_OF_LANGUAGE_SPECIFIC_PUNCTUATION列表中,然后将其连接到string.punctuation以获得更完整的标点符号集。
punctuation = string.punctuation + [LIST_OF_LANGUAGE_SPECIFIC_PUNCTUATION]