You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python处理字典值替换偶发失效问题(德国邮编OSM查询场景)

问题原因分析
  • 首先你当前的代码缺少HTTP请求异常处理逻辑,urllib.request.urlopen在遇到请求超时、429频率限制、5xx服务端错误时会直接抛出异常,你没有对这部分逻辑做捕获和重试,一旦请求出错,当前邮编对应的community字段就不会被更新,直接进入下一轮循环。你提到的10997没有被打印,说明没有触发IndexError,大概率是请求阶段就出现了异常跳过了赋值逻辑。
  • 其次Nominatim API的返回结果存在不确定性,部分邮编的搜索结果第一条的display_name值和你原有community字段的Berlin, Stadt完全一致,会造成“没有替换成功”的假象,你可以在赋值前打印jsonData[0]['display_name']和原feature['community']的值做对比验证。
  • 你代码里的zipCodes[index] = feature是冗余语句,因为feature是字典类型,属于引用传递,你直接修改feature['community']的时候,zipCodes对应位置的元素已经被同步修改了,这行代码不会造成问题但没有实际作用。
修复建议

你可以参考如下逻辑优化代码:

import json
import urllib.request
import urllib.error
import time

with open('zip_codes_germany.json') as originalFile:
    zipCodes = json.load(originalFile)
    for index, feature in enumerate(zipCodes):
        if feature['place'] == 'Berlin':
            zipCode = feature['zipcode']
            newQuery = f"https://nominatim.openstreetmap.org/search?postalcode={zipCode}&country=Germany&format=json"
            max_retries = 3
            retry_count = 0
            success = False
            while retry_count < max_retries and not success:
                try:
                    with urllib.request.urlopen(newQuery, timeout=10) as response:
                        if response.getcode() == 200:
                            jsonData = json.loads(response.read())
                            if jsonData and 'display_name' in jsonData[0]:
                                feature['community'] = jsonData[0]['display_name']
                                success = True
                        else:
                            print(f"邮编{zipCode}请求返回状态码:{response.getcode()}")
                except urllib.error.URLError as e:
                    print(f"邮编{zipCode}请求出错:{e.reason}")
                    retry_count += 1
                    time.sleep(5)
                except IndexError:
                    print(f"邮编{zipCode}无匹配结果")
                    break
            time.sleep(2)
    with open('zip_codes_germany_2.0.json', 'w') as newFile:
        newFile.write(json.dumps(zipCodes, ensure_ascii=False, indent=2))

内容的提问来源于stack exchange,提问作者four-eyes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 19:24:03