如何用 Python 获取邮政编码

发布时间:2022-07-24

在本教程中,我们将讨论如何使用 Python 中的地理模块获取特定位置的邮政编码。地质公园让 Python 用户可以轻松定位全球地址、城市和国家的坐标。 要安装 Geopy 模块,用户可以运行以下命令:

pip3 install geopy

如何获取邮政编码

我们将遵循以下步骤:

  • 步骤 1: 导入地质模块
  • 步骤 2: 初始化命名空间API,从输入字符串中获取位置。
  • 第三步:我们将使用 geo_locator.geocode() 函数获取位置。
  • 第四步:从给定的列表中获取信息,使用 raw 函数解析到字典中
  • 步骤 5: 从位置实例中提取 Zip 数据。 步骤 1: 导入地质模块
from geopy.geocoders import Nominatim

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

geo_locator = Nominatim(user_agent = "geoapiExercises")

第三步:使用 geocode() 函数获取完整地址

place_1 = "RidgePoint Irving, Texas, USA"
location = geo_locator.geocode(place_1)
print(location)

输出:

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

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

data_1 = location.raw
print (data_1)

输出:

{' 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: 从位置实例中提取 Zip 数据。

location_data = data_1['display_name'].split()
print ("The Full Location is: ")
print (location_data)
print ("The Zip code of the location is: ", location_data[-3])

输出:

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

Python 代码的完全实现

示例-

from geopy.geocoders import Nominatim
geo_locator = Nominatim(user_agent = "geoapiExercises")
place_1 = "Disneyland Dr, Anaheim, USA"
location = geo_locator.geocode(place_1)
print(location)
data_1 = location.raw
print (data_1)
location_data = data_1['display_name'].split()
print ("\nThe Full Location is: ")
print (location_data)
print ("The Zip code of the location is: ", location_data[-3])

输出:

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 模块获取给定位置的邮政编码。我们还展示了更好理解的例子。