2011-11-13 12 views
7

Voglio rimuovere tutti i tipi di sequenze di escape da un elenco di stringhe. Come posso fare questo? Ingresso:Come rimuovere tutte le sequenze di escape da un elenco di stringhe?

['william', 'short', '\x80', 'twitter', '\xaa', '\xe2', 'video', 'guy', 'ray'] 

uscita:

['william', 'short', 'twitter', 'video', 'guy', 'ray'] 

http://docs.python.org/reference/lexical_analysis.html#string-literals

+1

L'oggetto stringa finale non contiene alcuna informazione se il letterale stringa che lo contrasta conteneva una sequenza di escape. Se non sai nemmeno dire se ce ne sono, come li "rimuovi"? –

risposta

8

qualcosa di simile?

>>> from ast import literal_eval 
>>> s = r'Hello,\nworld!' 
>>> print(literal_eval("'%s'" % s)) 
Hello, 
world! 

Edit: ok, questo non è ciò che si desidera. Quello che vuoi non può essere fatto in generale, perché, come ha spiegato @Sven Marnach, le stringhe non contengono effettivamente sequenze di escape. Quelle sono solo notazioni in stringhe letterali.

È possibile filtrare tutte le stringhe con caratteri non-ASCII dalla vostra lista con

def is_ascii(s): 
    try: 
     s.decode('ascii') 
     return True 
    except UnicodeDecodeError: 
     return False 

[s for s in ['william', 'short', '\x80', 'twitter', '\xaa', 
      '\xe2', 'video', 'guy', 'ray'] 
if is_ascii(s)] 
3

Si potrebbe filtrare fuori "parole" che non sono alfanumerica tramite una lista di comprensione e str.isalnum():

>>> l = ['william', 'short', '\x80', 'twitter', '\xaa', '\xe2', 'video', 'guy', 'ray'] 
>>> [word for word in l if word.isalnum()] 
['william', 'short', 'twitter', 'video', 'guy', 'ray'] 

Se si desidera filtrare i numeri, utilizzare str.isalpha() invece:

>>> l = ['william', 'short', '\x80', 'twitter', '\xaa', '\xe2', 'video', 'guy', 'ray', '456'] 
>>> [word for word in l if word.isalpha()] 
['william', 'short', 'twitter', 'video', 'guy', 'ray'] 
+1

Questa è una buona risposta per molte applicazioni, anche se va notato che anche altri caratteri non alfanumerici come gli spazi bianchi subiranno l'ascia. –

2

Questo non può essere fatto, almeno per l'ampia portata che stai chiedendo. Come altri hanno già accennato, runtime python non conosce la differenza tra qualcosa con sequenze di escape e qualcosa senza.

Esempio:

print ('\x61' == 'a') 

stampe True. Quindi non c'è modo di trovare la differenza tra queste due stringhe, a meno che non provi qualche analisi statica del tuo script python.

20

Se si vuole mettere a nudo fuori alcuni personaggi che non ti piace, è possibile utilizzare la funzione di translate mettere a nudo fuori:

>>> s="\x01\x02\x10\x13\x20\x21hello world" 
>>> print(s) 
!hello world 
>>> s 
'\x01\x02\x10\x13 !hello world' 
>>> escapes = ''.join([chr(char) for char in range(1, 32)]) 
>>> t = s.translate(None, escapes) 
>>> t 
' !hello world' 

Questo eliminerà tutti questi caratteri di controllo:

001 1  01 SOH (start of heading) 
    002 2  02 STX (start of text) 
    003 3  03 ETX (end of text) 
    004 4  04 EOT (end of transmission) 
    005 5  05 ENQ (enquiry) 
    006 6  06 ACK (acknowledge) 
    007 7  07 BEL '\a' (bell) 
    010 8  08 BS '\b' (backspace) 
    011 9  09 HT '\t' (horizontal tab) 
    012 10 0A LF '\n' (new line) 
    013 11 0B VT '\v' (vertical tab) 
    014 12 0C FF '\f' (form feed) 
    015 13 0D CR '\r' (carriage ret) 
    016 14 0E SO (shift out) 
    017 15 0F SI (shift in) 
    020 16 10 DLE (data link escape) 
    021 17 11 DC1 (device control 1) 
    022 18 12 DC2 (device control 2) 
    023 19 13 DC3 (device control 3) 
    024 20 14 DC4 (device control 4) 
    025 21 15 NAK (negative ack.) 
    026 22 16 SYN (synchronous idle) 
    027 23 17 ETB (end of trans. blk) 
    030 24 18 CAN (cancel) 
    031 25 19 EM (end of medium) 
    032 26 1A SUB (substitute) 
    033 27 1B ESC (escape) 
    034 28 1C FS (file separator) 
    035 29 1D GS (group separator) 
    036 30 1E RS (record separator) 
    037 31 1F US (unit separator) 
+0

Scusa, quel giro mi fa solo rabbrividire. 'escapes = '' .join ([chr (char) per char nell'intervallo (1, 32)])' 's.translate (None, escape)' – Rebs

+0

@AdamGriffiths, è un bel cambiamento. Grazie. – sarnold

+0

Mi piace questa risposta piuttosto che la prima. funziona bene e molto flessibile. – weefwefwqg3

0

ho avuto problemi simili durante la conversione da hexadimal a String.This è quello che alla fine ha funzionato in python Esempio

list_l = ['william', 'short', '\x80', 'twitter', '\xaa', '\xe2', 'video', 'guy', 'ray'] 
decode_data=[] 
for l in list_l: 
    data =l.decode('ascii', 'ignore') 
    if data != "": 
     decode_data.append(data) 

# output :[u'william', u'short', u'twitter', u'video', u'guy', u'ray'] 
Problemi correlati