Zdá sa, že by mal existovať jednoduchší spôsob ako:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
Existuje?
Z hľadiska efektívnosti sa vám nepodarí poraziť
s.translate(None, string.punctuation)
Pre vyššie verzie Pythonu použite nasledujúci kód:
s.translate(str.maketrans('', '', string.punctuation))
Vykonáva operácie so surovými reťazcami v jazyku C pomocou vyhľadávacej tabuľky - nie je toho veľa, čo by to prekonalo, ale napíšte si vlastný kód v jazyku C.
Ak vás netrápi rýchlosť, je tu iná možnosť:
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
Je to rýchlejšie ako s.replace s každým znakom, ale nebude to fungovať tak dobre ako iné ako pythonovské prístupy, ako sú regexy alebo string.translate, ako môžete vidieť z nižšie uvedených časov. Pri tomto type problému sa oplatí robiť to na čo najnižšej úrovni.
Časovanie kódu:
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)
Výsledkom sú nasledujúce výsledky:
sets : 19.8566138744
regex : 6.86155414581
translate : 2.12455511093
replace : 28.4436721802
Nie nevyhnutne jednoduchšie, ale iným spôsobom, ak ste lepšie oboznámení s rodinou re.
import re, string
s = "string. With. Punctuation?" # Sample string
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)