2016-11-09 1 views
6

: I 라틴-1으로 인코딩 작업 (I 분명히 UTF-8을 열 수 없습니다)Python3 : 라틴-1 변환 UTF-8 내 코드는 다음과 같습니다

for file in glob.iglob(os.path.join(dir, '*.txt')): 
    print(file) 
    with codecs.open(file,encoding='latin-1') as f: 
     infile = f.read() 

with codecs.open('test.txt',mode='w',encoding='utf-8') as f: 
    f.write(infile) 

파일 . 하지만 결과 파일을 utf-8에 쓰고 싶습니다.

하지만이 :

<Trans audio_filename="VALE_M11_070.MP3" xml:lang="español"> 
<Datos clave_texto=" VALE_M11_070" tipo_texto="entrevista_semidirigida"> 
<Corpus corpus="PRESEEA" subcorpus="ESESUMA" ciudad="Valencia" pais="España"/> 

대신이 (의 gedit에서)이된다 : 나는 터미널에 인쇄하는 경우

<Trans audio_filename="VALE_M11_070.MP3" xml:lang="espa뇃漀氀∀㸀ഀ਀㰀䐀愀琀`漀猀 挀氀愀瘀攀开琀攀砀琀漀㴀∀ 嘀䄀䰀䔀开䴀㄀㄀开 㜀 

, 그것은 정상 표시됩니다.

더욱 혼란 내가 리브레 오피스 라이터로 결과 파일을 열 때 내가 무엇을 얻을 수 있습니다 :

<#T#r#a#n#s# (and so on) 

그래서 내가 어떻게 제대로 UTF-8 문자열로 라틴어 1 문자열을 변환합니까? python2에서는 쉽지만 python3에서는 혼란 스럽습니다.

#infile = bytes(infile,'utf-8').decode('utf-8') 
#infile = infile.encode('utf-8').decode('utf-8') 
#infile = bytes(infile,'utf-8').decode('utf-8') 

를 어쨌든 난 항상 같은 이상한 출력으로 끝낼 :

나는 다른 조합으로 이미 이들에게 시도했다.

미리 감사드립니다.

편집 :이 질문은 Python 3이 아닌 Python 2.7과 관련되어 있으므로 주석에 링크 된 질문과 다릅니다.

+1

먼저 디코드 문자열, 그런 다음 'utf-8'로 다시 인코딩 하시겠습니까? –

+2

가능한 복제본 http://stackoverflow.com/questions/6539881/python-converting-from-iso-8859-1-latin1-to-utf-8 – user3030010

+0

http://stackoverflow.com/questions/14443760/python- conversation-latin1-to-utf8 –

답변

0

나는 이것에서 절반 부분을 발견했다. 이것은 ... 당신은/필요를 원하지만, 올바른 방향으로 다른 사람을 도울 수있는 것이 아니다

# First read the file 
txt = open("file_name", "r", encoding="latin-1") # r = read, w = write & a = append 
items = txt.readlines() 
txt.close() 

# and write the changes to file 
output = open("file_name", "w", encoding="utf-8") 
for string_fin in items: 
    if "é" in string_fin: 
     string_fin = string_fin.replace("é", "é") 

    if "ë" in string_fin: 
     string_fin = string_fin.replace("ë", "ë") 

    # this works if not to much needs changing... 

    output.write(string_fin) 

output.close(); 

* 파이썬 3.6 detection

0

에 대한 참고 사항 :

your_str = your_str.encode('utf-8').decode('latin-1') 
관련 문제