Sembra che ci dovrebbe essere un modo più semplice di:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
C'è?
Dal punto di vista dell'efficienza, non si può battere
s.translate(None, string.punctuation)
Per le versioni superiori di Python usate il seguente codice:
s.translate(str.maketrans('', '', string.punctuation))
Esegue operazioni di stringhe grezze in C con una tabella di lookup - non c'è molto che possa battere questo, ma scrivere il proprio codice C.
Se la velocità non è una preoccupazione, un'altra opzione lo è:
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
Questo è più veloce di s.replace con ogni carattere, ma non si comporta bene come gli approcci non puri di python come le regex o string.translate, come potete vedere dai tempi qui sotto. Per questo tipo di problema, farlo al livello più basso possibile paga.
Codice dei tempi:
import re, string, timeit
s = "string. With. Punctuation"
exclude = set(string.punctuation)
table = string.maketrans("","")
regex = re.compile('[%s]' % re.escape(string.punctuation))
def test_set(s):
return ''.join(ch for ch in s if ch not in exclude)
def test_re(s): # From Vinko's solution, with fix.
return regex.sub('', s)
def test_trans(s):
return s.translate(table, string.punctuation)
def test_repl(s): # From S.Lott's solution
for c in string.punctuation:
s=s.replace(c,"")
return s
print "sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)
print "regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)
print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)
print "replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)
Questo dà i seguenti risultati:
sets : 19.8566138744
regex : 6.86155414581
translate : 2.12455511093
replace : 28.4436721802
Non necessariamente più semplice, ma un modo diverso, se avete più familiarità con la famiglia Re.
import re, string
s = "string. With. Punctuation?" # Sample string
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)