39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
import logging
|
|
|
|
|
|
def text_converter(texto, charset_destino='ISO8859_1', longitud_maxima=None):
|
|
"""
|
|
Convierte un texto al charset especificado, eliminando caracteres incompatibles.
|
|
|
|
Args:
|
|
texto (str): El texto a convertir.
|
|
charset_destino (str): El charset de destino (por defecto 'ISO8859_1').
|
|
longitud_maxima (int, opcional): La longitud máxima permitida para el texto convertido.
|
|
|
|
Returns:
|
|
str: El texto convertido al charset de destino.
|
|
"""
|
|
if not texto:
|
|
return ""
|
|
|
|
try:
|
|
# Convertir el texto al charset especificado
|
|
texto_convertido = texto.encode(
|
|
charset_destino, 'ignore').decode(charset_destino)
|
|
|
|
# Si se especifica una longitud máxima, truncar el texto
|
|
if longitud_maxima and len(texto_convertido) > longitud_maxima:
|
|
logging.warning(
|
|
f"El texto ha sido truncado de {len(texto_convertido)} a {longitud_maxima} caracteres.")
|
|
texto_convertido = texto_convertido[:longitud_maxima]
|
|
|
|
return texto_convertido
|
|
|
|
except UnicodeEncodeError as e:
|
|
logging.error(
|
|
f"Error al convertir texto a {charset_destino}: {str(e)}")
|
|
return ""
|
|
except Exception as e:
|
|
logging.error(f"Error inesperado al convertir texto: {str(e)}")
|
|
return ""
|