Uecko_ERP_FactuGES_sync/app/utils/text_converter.py

53 lines
1.7 KiB
Python

import logging
import re
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 ""
def limpiar_cadena(texto: str) -> str:
"""
Elimina espacios, guiones y cualquier carácter no alfanumérico.
Ejemplos:
'B 83999441' -> 'B83999441'
'B-83999441' -> 'B83999441'
'B_83 99-94.41' -> 'B83999441'
"""
if not isinstance(texto, str):
texto = str(texto)
return re.sub(r'[^A-Za-z0-9]', '', texto)