Python中如何替换字符串中的标点符号?

25
我想在Python中将字符串中的所有标点符号(而不是删除)替换为“ ”。
以下是否有类似以下代码效率高的方法?
text = text.translate(string.maketrans("",""), string.punctuation)

可能是Python中从字符串中删除标点的最佳方法的重复问题。 - Martijn Pieters
删除和替换为空之间有什么区别? - wroniasty
4
抱歉,我有些困惑,您需要我翻译的内容是什么?最后提到的是“no, replace with " "(空格)”,这是否意味着您并不需要我进行翻译?请让我知道更多信息,以便我可以更好地为您提供帮助。 - register
6个回答

49

这个答案是针对Python 2的,只适用于ASCII字符串:

string模块包含两个有用的函数:一个标点字符列表和"maketrans"函数。你可以按照以下方式使用它们:

import string
replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
text = text.translate(replace_punctuation)

2
这是最快的解决方案,轻松击败了正则表达式选项。 - Martijn Pieters
迄今为止最好的答案 - 快速而完整。 :-) - ProfVersaggi
1
在Python 3中使用以下代码:str.translate() https://docs.python.org/3/library/stdtypes.html#str.translate - jasonleonhard

21

Python中去除字符串中标点的最佳方法 修改得到的解决方案

import string
import re

regex = re.compile('[%s]' % re.escape(string.punctuation))
out = regex.sub(' ', "This is, fortunately. A Test! string")
# out = 'This is  fortunately  A Test  string'

1
你如何保留撇号,例如在 don't 这个单词中?我不想让撇号被去掉,以至于只剩下 dont。 - Chris Nielsen
2
你可以从string.punctuation中删除撇号(它本身只是一个包含所有标点符号字符的字符串)。 string.punctuation.replace("'", "") 将得到 '!"#$%&()*+,-./:;<=>?@[\\]^_{|}~'`。 - Gregor

2

有一种更强大的解决方案,它依赖于正则表达式的排除而不是通过一个包含大量标点符号字符的列表进行包含。

import re
print(re.sub('[^\w\s]', '', 'This is, fortunately. A Test! string'))
#Output - 'This is fortunately A Test string'

正则表达式会匹配任何非字母数字或空格字符。

2
这个解决办法适用于Python 3:

import string
ex_str = 'SFDF-OIU .df  !hello.dfasf  sad - - d-f - sd'
#because len(string.punctuation) = 32
table = str.maketrans(string.punctuation,' '*32) 
res = ex_str.translate(table)

# res = 'SFDF OIU  df   hello dfasf  sad     d f   sd' 

0
在我的特定方式中,我从标点符号列表中删除了“+”和“&”。
all_punctuations = string.punctuation
selected_punctuations = re.sub(r'(\&|\+)', "", all_punctuations)
print selected_punctuations

str = "he+llo* ithis& place% if you * here @@"
punctuation_regex = re.compile('[%s]' % re.escape(selected_punctuations))
punc_free = punctuation_regex.sub("", str)
print punc_free

结果:he+llo ithis& place if you here


0

''?替换。

将所有;翻译成''和删除所有;之间的区别是什么?

这里是删除所有;的方法:

s = 'dsda;;dsd;sad'
table = string.maketrans('','')
string.translate(s, table, ';')

你可以使用 translate() 函数进行替换。


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