2011-04-11 6 views
22

이진 데이터와 텍스트 데이터가 혼합 된 파일이 있습니다. 나는 정규 표현식을 통해 그것을 분석하고 싶지만,이 오류가 얻을 :바이너리 파일을 파싱하는 정규식?

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

내가 그 메시지를 추측하고있어 파이썬 바이너리 파일을 구문 분석하지 않는다는 것을 의미합니다. "rb" 플래그가있는 파일을 여는 중입니다.

파이썬에서 정규 표현식으로 이진 파일을 구문 분석하려면 어떻게해야합니까?

편집 : 내가 파이썬 3.2.0

+0

나는이 올바른지, 파이썬 3 사용하는 바이트와 같은 객체에 대한 참조에서 같은데요? –

답변

16

저는 파이썬 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

그런 다음, 파이썬 3에서, 파일에서 바이너리 스트림 때문에 바이트 스트림은, 정규식 파일에서 스트림을 분석 할 수는 바이트 순서가 아닌 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

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

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

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

하고 다음과 같이 그럼 당신은 정규식을 정의하지 않습니다

등 여기 3,691,363,210
pat = re.compile('[a-f]+\d+') 

자세한 설명은 :

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

+0

나중에 참조 할 수 있도록 _why_를 설명하기 때문에 Upvoted. 나는 인코딩이 무엇인지, 그리고 당신의 포스트가 너무 장황했다는 것을 알고있다.하지만 결국에는 내가 필요한 답을 준다. – DonkeyMaster

+0

힌트를 얻으십시오! -) –

+1

@John Machin 무슨 뜻입니까? – eyquem

-2

이것은 파이썬 2.6

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

이 코드는'import re; r = re.compile ("(This)")); f = open (r "C : \ WINDOWS \ system32 \ mspaint.exe", "rb"); x = f.readline(); r.match (x) .groups()' 은 원래 게시물과 동일한 오류를 반환합니다. – DonkeyMaster

24

나를 위해 일하고을 사용하고 당신의 re.compile 당신은 초기에 의해 표시 bytes 객체를 사용할 필요가 b :

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

이것은 파이썬 3의 문자열 차이 s 및 바이트.

+1

이 답변은 올바른 방향으로 나를 안내해주었습니다. 정말 고마워요. – DonkeyMaster

관련 문제