どうやら、もっと簡単な方法があるようです:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
ありますか?
ベストアンサー1
効率性の観点から言えば、
s.translate(None, string.punctuation)
Python のより高いバージョンの場合は、次のコードを使用します。
s.translate(str.maketrans('', '', string.punctuation))
これは、ルックアップ テーブルを使用して C で生の文字列操作を実行することです。独自の C コードを記述する以外に、これに勝るものはあまりありません。
速度が問題にならない場合は、別のオプションがあります。
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
これは各文字の s.replace よりも高速ですが、以下のタイミングからわかるように、正規表現や string.translate などの非純粋な Python アプローチほどパフォーマンスは良くありません。このタイプの問題では、できるだけ低いレベルで実行すると効果的です。
タイミングコード:
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)
これにより、次の結果が得られます。
sets : 19.8566138744
regex : 6.86155414581
translate : 2.12455511093
replace : 28.4436721802