2011-04-27 18 views
9

Estoy tratando de convertir el contenido del archivo de Windows-1251 (cirílico) a Unicode con Python. Encontré esta función, pero no funciona.Python: cómo convertir de Windows 1251 a Unicode?

#!/usr/bin/env python 

import os 
import sys 
import shutil 

def convert_to_utf8(filename): 
# gather the encodings you think that the file may be 
# encoded inside a tuple 
encodings = ('windows-1253', 'iso-8859-7', 'macgreek') 

# try to open the file and exit if some IOError occurs 
try: 
    f = open(filename, 'r').read() 
except Exception: 
    sys.exit(1) 

# now start iterating in our encodings tuple and try to 
# decode the file 
for enc in encodings: 
    try: 
     # try to decode the file with the first encoding 
     # from the tuple. 
     # if it succeeds then it will reach break, so we 
     # will be out of the loop (something we want on 
     # success). 
     # the data variable will hold our decoded text 
     data = f.decode(enc) 
     break 
    except Exception: 
     # if the first encoding fail, then with the continue 
     # keyword will start again with the second encoding 
     # from the tuple an so on.... until it succeeds. 
     # if for some reason it reaches the last encoding of 
     # our tuple without success, then exit the program. 
     if enc == encodings[-1]: 
      sys.exit(1) 
     continue 

# now get the absolute path of our filename and append .bak 
# to the end of it (for our backup file) 
fpath = os.path.abspath(filename) 
newfilename = fpath + '.bak' 
# and make our backup file with shutil 
shutil.copy(filename, newfilename) 

# and at last convert it to utf-8 
f = open(filename, 'w') 
try: 
    f.write(data.encode('utf-8')) 
except Exception, e: 
    print e 
finally: 
    f.close() 

¿Cómo puedo hacer eso?

Gracias

+0

¿Qué codificación quiere decir con [Unicode] (http://en.wikipedia.org/wiki/Unicode)? – Gumbo

+0

@Gumbo, a juzgar por el código, la salida debe ser UTF-8. –

Respuesta

10
import codecs 

f = codecs.open(filename, 'r', 'cp1251') 
u = f.read() # now the contents have been transformed to a Unicode string 
out = codecs.open(output, 'w', 'utf-8') 
out.write(u) # and now the contents have been output as UTF-8 

¿Es esto lo que pretende hacer?

+0

¡Creo que estás muy cerca! Logré leer los datos de XML, pero cuando lo escribo en el archivo, obtengo caracteres extraños en lugar de caracteres cirílicos. – Alex

+0

¡SÍ! ¡Entiendo! Estaba usando cp1252 en su lugar. Muchas gracias – Alex

+0

@Alex, me alegra saber que tu código funcionaba. Es posible que desee echar un vistazo a http://www.evanjones.ca/python-utf8.html, algunos buenos consejos allí. – buruzaemon

0

Si se utiliza el módulo de codecs para abrir el archivo, que va a hacer la conversión a Unicode para usted cuando se lee desde el archivo. Por ejemplo:

import codecs 
f = codecs.open('input.txt', encoding='cp1251') 
assert isinstance(f.read(), unicode) 

Esto solo tiene sentido si está trabajando con los datos del archivo en Python. Si intenta convertir un archivo de una codificación a otra en el sistema de archivos (que es lo que la secuencia de comandos que ha publicado intenta hacer), tendrá que especificar una codificación real, ya que no puede escribir un archivo en " Unicode ".

+0

Todavía aparece un error UnicodeEncodeError: el códec 'charmap' no puede codificar caracteres en posición: mapas de caracteres a Alex

+0

¿Cuál es el código real que está usando? ¿Qué línea desencadena esta excepción? –

+0

Aparece un error en f = abrir (nombre de archivo, 'r'). Read() – Alex

0

Esto es solo una suposición, ya que no especificó lo que quiere decir con "no funciona".

Si el archivo se está generando correctamente pero parece contener caracteres basura, es probable que la aplicación con la que lo está viendo no reconozca que contiene UTF-8. Necesita agregar una lista de materiales al principio del archivo: los 3 bytes 0xEF,0xBB,0xBF (sin codificar).

+0

Aparece un error en f = abrir (nombre de archivo, 'r'). Read() – Alex

Cuestiones relacionadas