SORU
5 Kasım 2008, ÇARŞAMBA


En iyi Python ile bir dize şerit noktalama işaretlerine yol

Daha basit bir yolu olmalı gibi görünüyor:

import string
s = "string. With. Punctuation?" # Sample string 
out = s.translate(string.maketrans("",""), string.punctuation)

Orada mı?

CEVAP
5 Kasım 2008, ÇARŞAMBA


Bir verimlilik bakış açısı, gitmeyeceksin, değil dövmek translate() - gerçekleştirme ham dize işlemleri C ile bir arama tablosu - pek bir şey yok bu olacak yendi o bar senin yazma kendi C kodu. Eğer hızlı bir endişe değil ise, başka bir seçenek:

exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)

Bu s daha hızlı.her char ile değiştirin, ama yanı sıra olmayan saf istemezler python yukarıdaki diyagram ya da ip gibi yaklaşımlar.zamanlamaları aşağıda gördüğünüz gibi çevirmek. Bu tür bir sorun için, mümkün olduğunca düşük bir seviyede yapıyor kapalı öder.

Kod zamanlama:

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)

Bu aşağıdaki sonuçları verir:

sets      : 19.8566138744
regex     : 6.86155414581
translate : 2.12455511093
replace   : 28.4436721802

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • DudeFromUkraine

    DudeFromUkra

    7 Ocak 2008
  • itfigueres

    itfigueres

    12 EKİM 2013
  • Rayone GB

    Rayone GB

    14 Temmuz 2007