2011-01-31 19 views
8

Ho questo simpatico piccolo metodo per rimuovere i caratteri di controllo da una stringa. Sfortunatamente, non funziona in Python 2.6 (solo in Python 3.1). Essa afferma:Maketrans in Python 2.6

mpa = str.maketrans(dict.fromkeys(control_chars)) 

AttributeError: type object 'str' has no attribute 'maketrans'

def removeControlCharacters(line): 
    control_chars = (chr(i) for i in range(32)) 
    mpa = str.maketrans(dict.fromkeys(control_chars)) 
    return line.translate(mpa) 

come può essere riscritto?

risposta

8

Per questo esempio, non v'è alcuna necessità di maketrans sia per le stringhe di byte o stringhe Unicode:

Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> delete_chars=''.join(chr(i) for i in xrange(32)) 
>>> '\x00abc\x01def\x1fg'.translate(None,delete_chars) 
'abcdefg' 

o:

Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> delete_chars = dict.fromkeys(range(32)) 
>>> u'\x00abc\x01def\x1fg'.translate(delete_chars) 
u'abcdefg' 

o anche in Python 3:

Python 3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> delete_chars = dict.fromkeys(range(32)) 
>>> '\x00abc\x01def\x1fg'.translate(delete_chars) 
'abcdefg' 

Vedere help(str.translate) e help(unicode.translate) (in Python2) per i dettagli.

+1

Per coloro che potrebbero provare qualcosa come il secondo esempio ... se si ottiene l'errore "TypeError: expected a character buffer object", potrebbe significare che la stringa che si sta tentando di tradurre non è unicode. (Indubbiamente questo è ovvio per Mark, ma non per i noobs come me.) – LarsH

14

In Python 2.6, maketrans è in the string module. Lo stesso con Python 2.7.

Quindi invece di str.maketrans, devi prima import string e quindi utilizzare string.maketrans.

Problemi correlati