2011-04-11 11 views
22

Tengo un archivo que mezcla datos binarios y datos de texto. Quiero analizar a través de una expresión regular, pero me sale este error:Expresión regular de analizar un archivo binario?

TypeError: can't use a string pattern on a bytes-like object 

supongo que el mensaje significa que Python no quiere analizar archivos binarios. Estoy abriendo el archivo con los indicadores "rb".

¿Cómo puedo analizar archivos binarios con expresiones regulares en Python?

EDIT: estoy usando Python 3.2.0

+0

que supongo de la referencia a objeto bytes-como que está utilizando Python 3, ¿es correcto? –

Respuesta

16

Creo que usas Python 3.

1.Opening a file in binary mode is simple but subtle. The only difference from opening it in text mode is that the mode parameter contains a 'b' character.

........

4.Here’s one difference, though: a binary stream object has no encoding attribute. That makes sense, right? You’re reading (or writing) bytes, not strings, so there’s no conversion for Python to do.

http://www.diveintopython3.net/files.html#read

Luego, en Python 3, ya que un flujo binario a partir de un archivo es una secuencia de bytes, una expresión regular para analizar una corriente de un archivo deben ser definidas con una secuencia de bytes, no una secuencia charcaters.

In Python 2, a string was an array of bytes whose character encoding was tracked separately. If you wanted Python 2 to keep track of the character encoding, you had to use a Unicode string (u'') instead. But in Python 3, a string is always what Python 2 called a Unicode string — that is, an array of Unicode characters (of possibly varying byte lengths).

http://www.diveintopython3.net/case-study-porting-chardet-to-python-3.html

y

In Python 3, all strings are sequences of Unicode characters. There is no such thing as a Python string encoded in UTF-8, or a Python string encoded as CP-1252. “Is this string UTF-8?” is an invalid question. UTF-8 is a way of encoding characters as a sequence of bytes. If you want to take a string and turn it into a sequence of bytes in a particular character encoding, Python 3 can help you with that.

http://www.diveintopython3.net/strings.html#boring-stuff

y

4.6. Strings vs. Bytes# Bytes are bytes; characters are an abstraction. An immutable sequence of Unicode characters is called a string. An immutable sequence of numbers-between-0-and-255 is called a bytes object.

....

1.To define a bytes object, use the b' ' “byte literal” syntax. Each byte within the byte literal can be an ASCII character or an encoded hexadecimal number from \x00 to \xff (0–255).

http://www.diveintopython3.net/strings.html#boring-stuff

Así que va a definir su expresión regular de la siguiente manera

pat = re.compile(b'[a-f]+\d+') 

y no como

pat = re.compile('[a-f]+\d+') 

Más explicaciones aquí:

15.6.4. Can’t use a string pattern on a bytes-like object

+0

Votación al alza porque explica el _por qué_, para referencia en el futuro. Entiendo lo que es una codificación, y tu publicación fue demasiado detallada, aunque a fin de cuentas das la respuesta que necesitaba. – DonkeyMaster

+0

¡Tome una pista! -) –

+1

@John Machin ¿Qué quiere decir, por favor? – eyquem

-2

Esto es trabajo para mí para el pitón 2,6

>>> import re 
>>> r = re.compile(".*(ELF).*") 
>>> f = open("/bin/ls") 
>>> x = f.readline() 
>>> r.match(x).groups() 
('ELF',) 
+0

Este código 'import re; r = re.compile ("(Esto)"); f = abrir (r "C: \ WINDOWS \ system32 \ mspaint.exe", "rb"); x = f.readline(); r.match (x) .groups() ' devuelve el mismo error que mi publicación original – DonkeyMaster

24

En su re.compile es necesario utilizar un objeto bytes, representado por una inicial b:

r = re.compile(b"(This)") 

Esta es Python 3 siendo exigente con la diferencia entre cuerdas s y bytes.

+1

Esta respuesta me puso en el camino correcto, muchas gracias. – DonkeyMaster

Cuestiones relacionadas