import json,time,urllib.request,urllib.parse,re,sys st=json.load(open('stage1.json',encoding='utf-8')) def get(u): time.sleep(0.4) try: return json.load(urllib.request.urlopen(urllib.request.Request(u,headers={'User-Agent':'theo-gastinel-perso-meteo/1.0'}),timeout=20)) except Exception as e: return {'features':[]} def variants(n): n=re.sub(r'\bST\b','SAINT',n); n=re.sub(r'\bSTE\b','SAINTE',n) v=[n, n.replace('-',' '), re.split(r'\s*[-/]\s*',n)[0]] return list(dict.fromkeys(v)) OKDEP={'01','38','39','73','74','69','42'} res={} for s in st: if s['lat'] is not None or s['pays']!='FR': continue deps={s['departement']} if s['departement']!='01' or True else None deps={s['departement']} if s['departement']=='01' and s['commune'] is None: deps=OKDEP hit=None for v in variants(s['nom_source']): for idx,extra in (('poi',''),('address','&type=municipality')): d=get('https://data.geopf.fr/geocodage/search?'+urllib.parse.urlencode({'q':v,'index':idx,'limit':10})+extra) for f in d['features']: p=f['properties']; dc=p.get('depcode'); dc=dc[0] if isinstance(dc,list) else dc if dc in deps: c=f['geometry']['coordinates']; city=p.get('city'); city=city[0] if isinstance(city,list) else city hit=(c[1],c[0],city,dc,idx,p.get('toponym') or p.get('name'),v);break if hit:break if hit:break res[s['id_romma']]=hit print(s['id_romma'],s['nom_source'],hit,flush=True) json.dump(res,open('geo_fr.json','w',encoding='utf-8'),ensure_ascii=False)