如何在 Python 中获取邮政编码

2025年3月17日 | 阅读 3 分钟

在本教程中,我们将讨论如何使用 Python 中的 geopy 模块获取特定位置的邮政编码。geopy 使 Python 用户可以轻松地定位全球地址、城市和国家/地区的坐标。

要安装 Geopy 模块,用户可以运行以下命令

如何获取邮政编码

我们将遵循以下步骤

  • 步骤 1:导入 geopy 模块
  • 步骤 2:初始化 Nominatim API 以从输入字符串获取位置。
  • 步骤 3:我们将使用 geo_locator.geocode() 函数获取位置。
  • 步骤 4:从给定列表中获取信息,并使用 ray function() 将其解析到字典中
  • 步骤 5:从 location 实例中提取 Zip 数据。

步骤 1:导入 geopy 模块

步骤 2:创建 Nominatim 对象,并使用 geoapiExercises 参数初始化 Nominatim API。

步骤 3:使用 geocode() 函数获取完整地址

输出

Ridgepoint Drive, Irving, Dallas County, Texas, 75063, United States

步骤 4:从给定列表中获取信息,并使用 raw 将其解析到字典中。

输出

{' place_id ': 209975995, ' licence ': ' Data � OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright ', ' osm_type ': ' way ', ' osm_id ': 567473012, ' boundingbox ': [' 32.908872 ', ' 32.9091407 ', ' -96.9887504 ', ' -96.9883353 '], ' lat ': ' 32.9088978 ', ' lon ': ' -96.9886835 ', ' display_name ':       ' Ridgepoint Drive, Irving, Dallas County, Texas, 75063, United States ', ' class ': 'highway ', ' type ': ' tertiary ', ' importance ': 0.42000000000000004}

步骤 5:从 location 实例中提取 Zip 数据。

输出

The Full Location is: 
['Ridgepoint', 'Drive,', 'Irving,', 'Dallas', 'County,', 'Texas,', '75063,', 'United', 'States']
The Zip code of the location is:  75063,

Python 代码完整实现

示例 -

输出

Disneyland Drive, Anaheim, Orange County, California, 92812-9998, United States
{' place_id ': 211571693, ' licence ': ' Data � OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright ', ' osm_type ': ' way ', ' osm_id ': 568143583, ' boundingbox ': [' 33.8184966 ', ' 33.8200236 ', ' -117.9229381 ', ' -117.9224363 '], ' lat ': ' 33.819073 ', ' lon ': ' -117.9226168 ', ' display_name ': 'Disneyland Drive, Anaheim, Orange County, California, 92812-9998, United States ', ' class ': ' highway ', ' type ': ' secondary ', ' importance ': 0.41000000000000003}

The Full Location is: 
['Disneyland', 'Drive,', 'Anaheim,', 'Orange', 'County,', 'California,', '92812-9998,', 'United', 'States']
The Zip code of the location is:  92812-9998,

结论

在本教程中,我们讨论了用户如何使用 Python 中的 geopy 模块获取给定位置的邮政编码。为了更好地理解,我们还展示了示例。


下一主题Python 中的 Eel