如何在Python中替换字符串中的标点符号?
我想用Python中字符串中的“”替换(而不是删除)所有标点字符 有以下味道的有效成分吗如何在Python中替换字符串中的标点符号?,python,string,replace,Python,String,Replace,我想用Python中字符串中的“”替换(而不是删除)所有标点字符 有以下味道的有效成分吗 text = text.translate(string.maketrans("",""), string.punctuation) 改性溶液 此答案适用于Python 2,仅适用于ASCII字符串: 字符串模块包含两个帮助您的功能:标点符号列表和“maketrans”函数。以下是如何使用它们: import string replace_punctuation = string.maketrans(st
text = text.translate(string.maketrans("",""), string.punctuation)
改性溶液
此答案适用于Python 2,仅适用于ASCII字符串: 字符串模块包含两个帮助您的功能:标点符号列表和“maketrans”函数。以下是如何使用它们:
import string
replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
text = text.translate(replace_punctuation)
替换为“”?
翻译所有的有什么区别将>编码到“”并删除所有代码>
这里是删除所有代码>:
s = 'dsda;;dsd;sad'
table = string.maketrans('','')
string.translate(s, table, ';')
您可以用translate来替换。以我的特定方式,我从标点符号列表中删除了“+”和“&”:
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
结果:如果你在这里,他将是&place此解决方案在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'
有一个更健壮的解决方案,它依赖于正则表达式排除,而不是通过大量标点符号列表包含
import re
print(re.sub('[^\w\s]', '', 'This is, fortunately. A Test! string'))
#Output - 'This is fortunately A Test string'
正则表达式捕获任何不是字母数字或空格字符的内容删除与替换之间可能存在的差异是什么?不,替换为“”(空格)。这是最快的解决方案,很容易击败正则表达式选项。到目前为止,最佳答案-快速且完整。:-)在Python3中使用以下命令:str.translate()如何保留撇号,例如在单词don't中?我不想去掉撇号,这样我就剩下dont了。你可以从string.标点符号中删除撇号(这是一个包含所有标点符号的字符串)<代码>字符串.标点符号.替换(“,”)
导致“.”!“#$%&()*+,-./:;?@[\]^
{124;}~”
import re
print(re.sub('[^\w\s]', '', 'This is, fortunately. A Test! string'))
#Output - 'This is fortunately A Test string'