2012-09-15 103 views
14

我想通過Python中的字符串替換(而不是刪除)所有標點符號。 有什麼有效的本味:如何替換字符串python中的標點符號?

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

感謝 寄存器

+0

s = s.replace('old','new') –

+0

可能的重複[在Python中刪除標點符號的最佳方式](http:// stackoverf low/quests/265960/best-way-to-strip-punctuation-from-a-string-in-python) –

+0

REMOVE與REPLACE之間有什麼區別? – wroniasty

回答

36

這個答案是Python的2只爲ASCII字符串的工作修改的方案:

字符串模塊包含兩件事會幫助你:一個標點符號列表acters和「maketrans」功能。以下是您如何使用它們:

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

這是最快的解決方案,很容易擊敗正則表達式選項。 –

+0

謝謝,這就是我正在爲之歡呼:) – register

+0

到目前爲止最好的答案 - 快速和完整。:-) – ProfVersaggi

9

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' 
+0

你會如何保留撇號,例如在單詞中不要?我不希望這些撇號被剝離出來,這樣我就不用離開了。 –

+0

您可以從string.punctuation中刪除撇號(這反過來只是一個包含所有標點符號的字符串)。 'string.punctuation.replace(「'」,「」)'導致''!「#$%&()* +, - 。/ :; <=>?@ [\\]^_'{|}〜 ' – Gregor

+0

Thanks!That works。 –

0

替換爲''? 翻譯所有';'有什麼區別?進入''並刪除所有';'? 這裏是刪除所有';'

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

,你可以做你的更換與翻譯

+0

誰知道爲什麼我有時不能使用代碼樣式? – cheneydeng

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 

結果:他+ LLO ithis &如果你在這裏

相關問題