2016-06-04 5 views
1

rockyou 단어 목록에서 읽으려고하고 = 8 자 이상의 모든 단어를 새 파일에 쓰려고합니다.파일을 읽을 때 UnicodeEncodeError

def main(): 
    with open("rockyou.txt", encoding="utf8") as in_file, open('rockout.txt', 'w') as out_file: 
     for line in in_file: 
      if len(line.rstrip()) < 8: 
       continue 
      print(line, file = out_file, end = '') 
     print("done") 

if __name__ == '__main__': 
    main() 

어떤 단어가 UTF-8로하지 않습니다 - 여기

는 코드입니다.

Traceback (most recent call last): File "wpa_rock.py", line 10, in <module> main() File "wpa_rock.py", line 6, in main print(line, file = out_file, end = '') File "C:\Python\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u0e45' in position 0: character maps to <undefined>

업데이트

def main(): 
with open("rockyou.txt", encoding="utf8") as in_file, open('rockout.txt', 'w', encoding="utf8") as out_file: 
    for line in in_file: 
     if len(line.rstrip()) < 8: 
      continue 
     out_file.write(line) 
    print("done") 

if __name__ == '__main__': 
    main()``` 

Traceback (most recent call last): File "wpa_rock.py", line 10, in <module> main() File "wpa_rock.py", line 3, in main for line in in_file: File "C:\Python\lib\codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 933: invali d continuation byte

+1

오타입니다. 그것은'utf8' 대신'utf-8'이어야합니다. – Arpan

+0

나는 그것이 있는지 모른다. 둘 중 하나를 사용하면 동일한 오류가 발생합니다. –

+0

해당 위치에 유효하지 않은 문자가 있어야합니다. 읽을 파일을 보여 주어야합니다. – Arpan

답변

1

귀하의 UnicodeEncodeError: 'charmap' 오류 (print()에서) out_file-를 작성 동안 발생합니다. 기본적으로

, open() 모든 유니 코드 문자 특히 '\u0e45' 문자를 표시 할 수 없습니다 Windows에서 ANSI 코드 페이지가 (예 cp1252)입니다 locale.getpreferredencoding()을 사용합니다. cp1252은 1 바이트 인코딩으로 최대 256 개의 다른 문자를 나타낼 수 있지만 백만 (1114111) 개의 유니 코드 문자가 있습니다. 그들 모두를 대표 할 수는 없습니다. 코드 -if 예를 들어, 원하는 모든 데이터를 표시 할 수

패스 encoding, encoding='utf-8'이 (@robyschek suggested로) 일을해야 오류없이 utf-8 데이터가 다음 코드가 너무 utf-8를 사용하여 데이터를 쓸 수 있어야 읽습니다.


귀하의 UnicodeDecodeError: 'utf-8' 오류가 in_file (for line in in_file를) 읽는 동안 발생합니다. 모든 바이트 시퀀스가 ​​유효한 utf-8 인 것은 아닙니다. 예를 들어 os.urandom(100).decode('utf-8')이 실패 할 수 있습니다. 수행 할 작업은 응용 프로그램에 따라 다릅니다.

파일을 utf-8로 인코딩해야합니다. 가끔 유효하지 않은 바이트 시퀀스를 무시하기 위해 errors="ignore"open() 매개 변수를 전달할 수 있습니다. 또는 some other error handlers depending on your application을 사용할 수도 있습니다.

파일에 사용 된 실제 문자 인코딩이 다른 경우 실제 문자 인코딩을 전달해야합니다. 스스로 bytes는 파일 내용이 HTTP 본문은 다음 때때로

A good way to get the charset/encoding of an HTTP response in Python을 볼 경우 예를 들어이 깨진 소프트웨어와 대부분 UTF-8 바이트 시퀀스를 생성 할 수 있습니다 (some encodings are more likely than others: chardet can guess을하지만) 다른 소스에서 와야 어떤 인코딩 - 메타 데이터가 없습니다 다른 인코딩의 일부 바이트 bs4.BeautifulSoup can handle some special cases. try ftfy utility/library 수 있으며 귀하의 경우에 도움이되는지 확인하십시오 (예 : ftfy may fix some utf-8 variations).

+0

질문이 업데이트되었습니다. –

관련 문제