似乎应该有一种比以下更简单的方法:

import string
s = "string. With. Punctuation?" # Sample string 
out = s.translate(string.maketrans("",""), string.punctuation)

有?


当前回答

字符串标点符号漏掉了现实世界中常用的大量标点符号。一个适用于非ASCII标点符号的解决方案怎么样?

import regex
s = u"string. With. Some・Really Weird、Non?ASCII。 「(Punctuation)」?"
remove = regex.compile(ur'[\p{C}|\p{M}|\p{P}|\p{S}|\p{Z}]+', regex.UNICODE)
remove.sub(u" ", s).strip()

我个人认为,这是在Python中删除字符串标点符号的最佳方法,因为:

它删除所有Unicode标点符号它很容易修改,例如,如果您想删除标点符号,可以删除\{s},但保留像$这样的符号。您可以非常具体地了解要保留的内容和要删除的内容,例如,Pd只会删除破折号。此正则表达式还规范了空白。它将制表符、回车符和其他奇怪的字符映射到漂亮的单个空格。

这使用了Unicode字符财产,您可以在Wikipedia上阅读更多有关该属性的信息。

其他回答

这个问题没有太多细节,所以我采取的方法是用最简单的解释来解决这个问题:去掉标点符号。

请注意,所提供的解决方案不考虑收缩词(例如,you are)或连字符词(例如肛门保留)。。。这是关于它们是否应该被视为标点符号的争论。。。也不能解释非英语字符集或类似的东西。。。因为问题中没有提到这些细节。有人认为空格是标点符号,这在技术上是正确的。。。但对我来说,这在当前问题的背景下毫无意义。

# using lambda
''.join(filter(lambda c: c not in string.punctuation, s))

# using list comprehension
''.join('' if c in string.punctuation else c for c in s)

我还没有看到这个答案。只需使用正则表达式;它删除了除单词字符(\w)和数字字符(\d)之外的所有字符,后跟一个空白字符(\s):

import re
s = "string. With. Punctuation?" # Sample string 
out = re.sub(ur'[^\w\d\s]+', '', s)

为了方便使用,我总结了Python 2和Python 3中从字符串中删除标点符号的注意事项。有关详细说明,请参阅其他答案。


Python 2

import string

s = "string. With. Punctuation?"
table = string.maketrans("","")
new_s = s.translate(table, string.punctuation)      # Output: string without punctuation

Python 3

import string

s = "string. With. Punctuation?"
table = str.maketrans(dict.fromkeys(string.punctuation))  # OR {key: None for key in string.punctuation}
new_s = s.translate(table)                          # Output: string without punctuation

不一定更简单,但如果你更熟悉re家族的话,就另辟蹊径。

import re, string
s = "string. With. Punctuation?" # Sample string 
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)

在不太严格的情况下,单行线可能会有所帮助:

''.join([c for c in s if c.isalnum() or c.isspace()])