mgilson test_re() ? re.sub() , .
python 3.4; string.translate() , dict. dict, . , ( ).
import re
import string
regex=re.compile('[^atgc]')
chars_to_remove = string.printable.translate({ ord('a'): None, ord('c'): None, ord('g'): None, ord('t'): None })
cmap = {}
for c in chars_to_remove:
cmap[ord(c)] = None
def test_re(s):
return regex.sub('',s)
def test_join1(s,chars_keep=set('atgc')):
return ''.join(c for c in s if c in chars_keep)
def test_join2(s,chars_keep=set('atgc')):
""" list-comp is faster, but less 'idiomatic' """
return ''.join([c for c in s if c in chars_keep])
def translate(s):
return s.translate(cmap)
import timeit
s = 'ag ct oso gcota'
for func in "test_re","test_join1","test_join2","translate":
print(func,timeit.timeit('{0}(s)'.format(func),'from __main__ import s,{0}'.format(func)))
:
test_re 3.3141989699797705
test_join1 2.4452173250028864
test_join2 2.081048655003542
translate 1.9390292020107154
Too bad string.translate () does not have the ability to control what to do with characters that are not on the map. The current implementation is to save them, but we could also be able to delete them, in those cases where the characters that we want to keep are much smaller than the ones that we want to delete (oh, hello, unicode).
Blued source
share