How do I replace punctuation in a string in Python?

会有一股神秘感。 提交于 2019-12-03 08:50:58

问题


I would like to replace (and not remove) all punctuation characters by " " in a string in Python.

Is there something efficient of the following flavour?

text = text.translate(string.maketrans("",""), string.punctuation)

回答1:


This answer is for Python 2 and will only work for ASCII strings:

The string module contains two things that will help you: a list of punctuation characters and the "maketrans" function. Here is how you can use them:

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



回答2:


Modified solution from Best way to strip punctuation from a string in 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'



回答3:


There is a more robust solution which relies on a regex exclusion rather than inclusion through an extensive list of punctuation characters.

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

The regex catches anything which is not an alpha-numeric or whitespace character




回答4:


Replace by ''?.

What's the difference between translating all ; into '' and remove all ;?

Here is to remove all ;:

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

And you can do your replacement with translate.




回答5:


In my specific way, I removed "+" and "&" from the punctuation list:

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

Result: he+llo ithis& place if you here




回答6:


This workaround works in 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' 


来源:https://stackoverflow.com/questions/12437667/how-do-i-replace-punctuation-in-a-string-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!