Skip to content

Commit c57da94

Browse files
committed
fix: normalize province names for cod_istat matching (encoding, spaces, 'di')
1 parent 57753c1 commit c57da94

2 files changed

Lines changed: 13 additions & 3 deletions

File tree

resources/build_territorial_subdivisions.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,13 +99,23 @@ def load_itter107(path: str) -> dict[str, str]:
9999
return codes
100100

101101

102+
def _normalize_name(name: str) -> str:
103+
"""Normalize province name for matching (escaped unicode, spaces, 'di ')."""
104+
import unicodedata
105+
s = re.sub(r'\\u([0-9a-fA-F]{4})', lambda m: chr(int(m.group(1), 16)), name)
106+
s = unicodedata.normalize('NFC', s)
107+
s = re.sub(r'\s*/\s*', '/', s) # "Bolzano / Bozen" → "Bolzano/Bozen"
108+
s = re.sub(r'\bdi\s+', '', s) # "Reggio di Calabria" → "Reggio Calabria"
109+
return s.lower()
110+
111+
102112
def build_mappings() -> tuple[dict, dict, dict, dict]:
103113
"""Build all territorial mappings from unit_territoriali.csv.
104114
105115
Returns:
106116
- comune_to_nuts3: cod_com (alfanumerico) → ITTER NUTS3
107117
- storico_to_nuts3: cod_prov_storico → ITTER NUTS3
108-
- name_to_cod_prov: province name → cod_prov (int string)
118+
- name_to_cod_prov: normalized province name → cod_prov (int string)
109119
- nuts2_to_cod_reg: ITTER NUTS2 → cod_reg (int string)
110120
"""
111121
comune_to_nuts3: dict[str, str] = {}
@@ -129,7 +139,7 @@ def build_mappings() -> tuple[dict, dict, dict, dict]:
129139
storico_to_nuts3[cod_prov] = itter
130140
nuts2_to_cod_reg[itter[:4]] = str(int(cod_reg))
131141
if den_uts and cod_prov:
132-
name_to_cod_prov[den_uts] = str(int(cod_prov))
142+
name_to_cod_prov[_normalize_name(den_uts)] = str(int(cod_prov))
133143

134144
print(f' comuni: {len(comune_to_nuts3)} | storico: {len(storico_to_nuts3)} | prov_names: {len(name_to_cod_prov)} | reg: {len(nuts2_to_cod_reg)}')
135145
return comune_to_nuts3, storico_to_nuts3, name_to_cod_prov, nuts2_to_cod_reg
@@ -196,7 +206,7 @@ def cod_rip(nuts1: str | None) -> str | None:
196206
for k, v in all_province_codes.items():
197207
parent = IT1XX_PARENTS.get(k, k[:4])
198208
nuts1 = IT1XX_PARENTS.get(k, k)[:3]
199-
rows.append((k, v, 'provincia', 3, parent, None, None, name_to_cod_prov.get(v), den_rip(nuts1), cod_rip(nuts1)))
209+
rows.append((k, v, 'provincia', 3, parent, None, None, name_to_cod_prov.get(_normalize_name(v)), den_rip(nuts1), cod_rip(nuts1)))
200210

201211
no_parent = 0
202212
for k, v in codes.items():
-256 KB
Binary file not shown.

0 commit comments

Comments
 (0)