-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxls_to_JSON.py
More file actions
144 lines (121 loc) · 4.32 KB
/
Copy pathxls_to_JSON.py
File metadata and controls
144 lines (121 loc) · 4.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import json
import re
import os
import sys
import unicodedata
from datetime import datetime
from openpyxl import load_workbook
# Forzar UTF-8 en la salida
if sys.platform == 'win32':
sys.stdout.reconfigure(encoding='utf-8')
# Tabla de reemplazos para caracteres mal codificados
REEMPLAZOS = {
# Vocales con acento (Windows-1252 a UTF-8)
'á': 'á', 'é': 'é', 'Ã': 'í', 'ó': 'ó', 'ú': 'ú',
'À': 'À', 'È': 'È', 'ÃŒ': 'Ì', 'Ã’': 'Ò', 'Ù': 'Ù',
'â': 'â', 'ê': 'ê', 'î': 'î', 'ô': 'ô', 'û': 'û',
# Ñ y Ü
'ñ': 'ñ', 'Ñ': 'Ñ', 'ü': 'ü', 'Ü': 'Ü',
# Símbolos comunes
'¡': '¡', '¿': '¿', '°': '°', '·': '·', '®': '®',
'©': '©', '§': '§', '¶': '¶',
# Comillas y apóstrofes
'“': '"', 'â€': '"', '‘': "'", '’': "'",
'‚': ',', '„': '"', '…': '...',
# Guiones
'—': '-', '–': '-',
# Problemas específicos de laboratorios
'Bag¿': 'Bagó',
'bag¿': 'Bagó',
'Cassarß': 'Cassará',
'cassarß': 'Cassará',
'Temis-Lostal¿': 'Temis-Lostaló',
'G¿minis Farmac¿': 'Géminis Farmacéutica',
'Andr¿maco': 'Andrómaco',
# Reemplazos generales para caracteres sueltos
'¿': 'ó',
'ß': 'á',
# Casos con espacios
'¿ ': 'ó ',
'ß ': 'á ',
}
def normalizar_nombre(texto):
"""Convierte a formato título: primeras letras mayúsculas"""
if not texto:
return ''
excepciones = {'y', 'de', 'la', 'del', 'los', 'las', 'con', 'sin', 'por', 'para', 'a', 'ante', 'bajo', 'cabe', 'contra', 'desde', 'durante', 'en', 'entre', 'hacia', 'hasta', 'mediante', 'segun', 'so', 'sobre', 'tras', 'el', 'un', 'una', 'y/o', 'e', 'u'}
palabras = texto.split()
resultado = []
for i, p in enumerate(palabras):
if i == 0 or p.lower() not in excepciones:
resultado.append(p[0].upper() + p[1:].lower() if len(p) > 1 else p.upper())
else:
resultado.append(p.lower())
return ' '.join(resultado)
def limpiar_texto(texto):
"""Limpia y normaliza texto, corrige acentos mal codificados"""
if not texto:
return ''
texto = str(texto)
for mal, bien in REEMPLAZOS.items():
texto = texto.replace(mal, bien)
texto = unicodedata.normalize('NFC', texto)
texto = re.sub(r'[^\x20-\x7E\xA0-\xFF\u0100-\uFFFF]', '', texto)
texto = re.sub(r'\s+', ' ', texto).strip()
texto = normalizar_nombre(texto)
return texto
def limpiar_precio(valor):
"""Limpia el precio y lo convierte a float"""
if not valor:
return 0
precio_raw = str(valor)
precio_limpio = re.sub(r'[^\d.,-]', '', precio_raw).replace(',', '.')
try:
return float(precio_limpio)
except:
return 0
# Buscar el archivo XLSX
archivo_xls = None
for archivo in os.listdir('.'):
if archivo.endswith('.xlsx'):
archivo_xls = archivo
break
if not archivo_xls:
print("❌ No hay archivo .xlsx en esta carpeta")
exit(1)
print(f"📄 Leyendo: {archivo_xls}")
wb = load_workbook(archivo_xls, data_only=True)
ws = wb.active
medicamentos = []
for row in ws.iter_rows(min_row=2, values_only=True):
if not row[0]:
continue
droga = limpiar_texto(row[0])
marca = limpiar_texto(row[1])
presentacion = limpiar_texto(row[2])
laboratorio = limpiar_texto(row[3])
cobertura = str(row[4]).replace('%', '').strip() if row[4] else '0'
copago = limpiar_precio(row[5])
medicamentos.append({
"DROGA": droga,
"MARCA": marca,
"PRESENTACION": presentacion,
"LABORATORIO": laboratorio,
"COBERTURA": cobertura,
"COPAGO": copago
})
fecha_actual = datetime.now().strftime("%d/%m/%Y %H:%M")
datos = {"fecha": fecha_actual, "medicamentos": medicamentos}
with open('medicamentos.json', 'w', encoding='utf-8') as f:
json.dump(datos, f, ensure_ascii=False, indent=2)
print(f"✅ {len(medicamentos)} medicamentos guardados")
print(f"📅 Fecha: {fecha_actual}")
# Mostrar muestra de laboratorios
labs = {}
for med in medicamentos:
lab = med['LABORATORIO']
if lab and lab not in labs:
labs[lab] = True
print("\n🔤 Muestra de laboratorios:")
for i, lab in enumerate(sorted(labs.keys())[:20]):
print(f" {i+1}. {lab}")