2017-12-18 31 views
0

안녕하세요 :) gzipped (큰 숫자는 blabla.bin.gz)입니다.파이썬 - 디코딩 오류 ('ascii'코덱은 위치 19의 바이트 0x94를 디코딩 할 수 없습니다 .....)

아스키 형식으로 txt 파일에 압축을 풀어 써야합니다. 다음은 내 코드입니다 :

import gzip 

with gzip.open("GoogleNews-vectors-negative300.bin.gz", "rb") as f: 

    file_content = f.read() 
    file_content.decode("ascii") 
    output = open("new_file.txt", "w", encoding="ascii") 
    output.write(file_content) 
    output.close() 

하지만이 오류가있어 :

file_content.decode("ascii") 
UnicodeDecodeError: 'ascii' codec can't decode byte 0x94 in position 19: ordinal not in range(128) 

내가 파이썬 만에 이렇게 새로운 아니에요을 형식/코딩 문제는 항상 있었다 나의 가장 큰 약점 :(

, 당신이 나를 도울 수 제발?

감사합니다!

+0

생각 :

file_content = file_content.decode("ascii", errors="ignore") # just remove any non ascii byte 

또는 당신이 정말로 모든 비 ASCII 문자를 필터링해야하는 경우

마침내, 당신은 디코드의 error 매개 변수를 사용할 수 있습니다 UTF8 또는 유니 코드 또는 이전의 모든 것? 이것 좀 봐 줄래? 128 비트 아스키로 처리하지 못했던 것이 있습니까? 그냥 낄낄 거리는 소리에 대해서 :'encoding = 'utf-8',''그냥 file_content.decode ("utf-8")'- utf-8에 익숙해 져야한다. –

+0

대신 다음을 사용해야합니다 : https://docs.python.org/3/library/binascii.html –

+1

'file_content.decode ('cp1252')'가 작동합니까? '0x94'는 cp1252에있는 닫는 둥근 큰 따옴표입니다. 이것은 Windows 시스템에서 일반적인 인코딩입니다. – snakecharmerb

답변

2

첫째, 아무 것도 디코딩하여 원시 바이트로 즉시 다시 쓸 이유가 없습니다. 그래서 간단하게 (더 강력한) 구현 될 수있다 :

with gzip.open("GoogleNews-vectors-negative300.bin.gz", "rb") as f: 

    file_content = f.read() 
    with open("new_file.txt", "wb") as output: # just directly write raw bytes 
     output.write(file_content) 

당신이 정말로 디코딩하고 싶지만 인코딩 모르는 경우, 당신은 라틴어를 사용할 수 있습니다. 모든 바이트는 Latin1에서 유효하며 동일한 값의 유니 코드 문자로 변환됩니다. 바이트 문자열 bs이 무엇이든 bs.decode('Latin1').encode('Latin1')bs입니다. gzip으로 압축 된 파일이 있었다 가능성에 대해

with gzip.open("GoogleNews-vectors-negative300.bin.gz", "rb") as f: 

    file_content = f.read() 
    file_content = file_content.decode("ascii", errors="replace") #non ascii chars are 
              # replaced with the U+FFFD replacement character 
    output = open("new_file.txt", "w", encoding="ascii", errors="replace") # non ascii chars 
                 # are replaced with a question mark "?" 
    output.write(file_content) 
    output.close() 
+0

감사합니다.하지만이 오류가 발생합니다 :'output.write (file_content) TypeError : write() 인수는 바이트가 아닌 str이어야합니다. '그래서 기본적으로 여전히 고려됩니다. –

+0

@inTaowetrust : 첫 번째 해결책에서,'file_content'는 바이트 문자열이고 출력 파일은 바이너리 모드 (''wb "')로 열리고, 두 번째'f ile_content'는 유니 코드 문자열이되고 파일은 텍스트 모드로 열립니다. 기다려 ... 나는'file_content'에 할당하는 것을 잊었다 :-(. 제 편집을 참조하십시오. –