"""ETIQ-3 · E9 · impl. 2 · banco ayuntamiento-año con casado PROPIO de las filas del Anexo 4 (lectura de DAT-2 sin casar, `anexo_entidades_AAAA.tsv`) por el padrón del INE: provincia (catálogo DIR3) + nombre normalizado → INE → NIF del censo. Uso (host): python3 -I e9_banco_i2.py """ import csv, sys, re, unicodedata, difflib, collections AN, REF, XPROV, XM, OUT = sys.argv[1:6] sys.path.insert(0, XM) from xlsx_min import hojas # noqa def sin(s): s = unicodedata.normalize('NFKD', (s or '').upper()) return ''.join(c for c in s if not unicodedata.combining(c)) ART = {'EL', 'LA', 'LOS', 'LAS', 'L', 'LES', 'ELS', 'O', 'A', 'OS', 'AS', 'SA', 'ES', 'SES', 'S', 'LO', 'DE', 'DEL', 'D', 'I', 'Y', 'E'} def claves(nombre): """Variantes de un nombre: entero y cada parte bilingüe, sin artículos ni preposiciones, letras y cifras.""" s = sin(nombre).replace("'", ' ').replace('’', ' ') s = re.sub(r'^(AYUNTAMIENTO|AJUNTAMENT|CONCELLO)( DE| DEL| D)?\s+', '', s) partes = [s] + re.split(r'\s*/\s*|\s+-\s+', s) out = set() for p in partes: m = re.match(r'^(.*),\s*(\w+)$', p.strip()) # «ACEBEDA, LA» if m: p = m.group(2) + ' ' + m.group(1) toks = [t for t in re.findall(r'[A-Z0-9]+', p) if t not in ART] if toks: out.add(''.join(toks)) return out prov = {} for r in hojas(XPROV)['Catálogo Provincia'][2:]: if len(r) > 2 and r[1] and r[1].isdigit(): for k in claves(r[2]): prov[k] = r[1] prov.update({'GERONA': '17', 'LERIDA': '25', 'ORENSE': '32', 'BALEARES': '07', 'ILLESBALEARS': '07', 'CORUNA': '15', 'ACORUNA': '15', 'PALMAS': '35', 'LASPALMAS': '35', 'RIOJA': '26', 'LARIOJA': '26', 'CASTELLON': '12', 'ALICANTE': '03', 'VALENCIA': '46'}) pad = {r['ine']: r for r in csv.DictReader(open(f'{REF}/padron_municipios_2019_2025.csv'))} idx = collections.defaultdict(set) for ine, r in pad.items(): for k in claves(r['municipio']): idx[(ine[:2], k)].add(ine) cen = {r['ine']: r for r in csv.DictReader(open(f'{REF}/censo_ay_dir3.tsv'), delimiter='\t')} def pob(ine, ej): r = pad.get(ine, {}) for y in [max(ej, 2019)] + list(range(2019, 2026)): if r.get(f'poblacion_{y}'): return int(r[f'poblacion_{y}']) return None def tramo(p): return '' if p is None else '1:<=1000' if p <= 1000 else '2:1001-5000' if p <= 5000 else '3:5001-20000' if p <= 20000 else '4:20001-50000' if p <= 50000 else '5:>50000' out, st = [], collections.Counter() for ej in range(2017, 2025): lab, dudosas = {}, [] for x in csv.DictReader(open(f'{AN}/anexo_entidades_{ej}.tsv'), delimiter='\t'): if x['tipo'] != 'AYUNTAMIENTO': continue pv = next((prov[k] for k in claves(x['provincia']) if k in prov), None) c = set() if pv: for k in claves(x['entidad']): c |= idx.get((pv, k), set()) if len(c) == 1: lab[next(iter(c))] = x else: dudosas.append((pv, x)) excl = set() for pv, x in dudosas: for k in claves(x['entidad']): for ine, r in pad.items(): if ine[:2] == pv and ine not in lab: for k2 in claves(r['municipio']): if difflib.SequenceMatcher(None, k, k2).ratio() >= 0.80 or k in k2 or k2 in k: excl.add(ine) for ine, c in sorted(cen.items()): if c['prov'] in ('01', '20', '48', '31') or not c['nif']: continue x = lab.get(ine) est = x['contratos'] if x else 'no_listado' rep = x['reparos'] if x else 'no_listado' if c['prov'] in ('08', '17', '25', '43') and ej in (2017, 2018, 2019, 2020, 2021, 2023): m = 'cataluna_NA' elif x is None and ine in excl: m = 'identidad_dudosa' else: m = '' y = None if m else (1 if est == 'NO' else 0 if est in ('SI', 'no_listado') else None) ys = None if m else (1 if est in ('NO', 'NO*') else 0 if est in ('SI', 'no_listado') else None) yr = None if m else (1 if rep == 'NO' else 0 if rep in ('SI', 'no_listado') else None) p = pob(ine, ej) out.append({'ejercicio': ej, 'nif': c['nif'], 'ine': ine, 'cod_ca': c['cod_ca'], 'poblacion': p, 'tramo': tramo(p), 'estado_contratos': est, 'motivo_fuera': m, 'y_nr': y, 'y_nrstar': ys, 'y_rep': yr}) st[(ej, m or ('NR' if y == 1 else 'neg' if y == 0 else 'fuera:' + est))] += 1 st[(ej, 'dudosas')] = len(dudosas) with open(OUT, 'w', newline='') as fh: w = csv.DictWriter(fh, list(out[0].keys()), delimiter='\t'); w.writeheader(); w.writerows(out) for ej in range(2017, 2025): print(ej, {k[1]: v for k, v in sorted(st.items()) if k[0] == ej})