从 Nominatim GeoPy 响应中获取国家

get country from Nominatim GeoPy response

当使用 NOminatim 和 GeoPy 对给定的地址字符串进行编码时,如何获取国家/地区信息?

有什么结构化的方法可以在输出中获取国家名称吗?一种方法是使用最后一个“,”之后的字符串来获取国家/地区,但这似乎不是一种可靠的方法。

from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent='myapplication')
x = 'PA - Cranberry Township'
location = geolocator.geocode(x, exactly_one=True,language="english", namedetails=True)
# how to get country name from response
location.raw


{'place_id': 259010359,
 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright',
 'osm_type': 'relation',
 'osm_id': 4131949,
 'boundingbox': ['40.673669', '40.7453357', '-80.1525583', '-80.0559393'],
 'lat': '40.7099343',
 'lon': '-80.1060506',
 'display_name': 'Cranberry Township, Butler County, Pennsylvania, 16066, United States',
 'class': 'boundary',
 'type': 'administrative',
 'importance': 0.6463910141518243,
 'icon': 'https://nominatim.openstreetmap.org/ui/mapicons//poi_boundary_administrative.p.20.png',
 'namedetails': {'name': 'Cranberry Township',
  'name:en': 'Cranberry Township',
  'official_name': 'Cranberry Township'}}

给你:

from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent='myapplication')
x = 'PA - Cranberry Township'
location = geolocator.geocode(x, exactly_one=True,language="english", namedetails=True, addressdetails=True)
print(location.raw)
print(f"""Country Name: {location.raw['address']['country']}""")

输出:

{
   "place_id":258908396,
   "licence":"Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
   "osm_type":"relation",
   "osm_id":4131949,
   "boundingbox":[
      "40.673669",
      "40.7453357",
      "-80.1525583",
      "-80.0559393"
   ],
   "lat":"40.7099343",
   "lon":"-80.1060506",
   "display_name":"Cranberry Township, Butler County, Pennsylvania, 16066, United States",
   "class":"boundary",
   "type":"administrative",
   "importance":0.6463910141518243,
   "icon":"https://nominatim.openstreetmap.org/ui/mapicons//poi_boundary_administrative.p.20.png",
   "address":{
      "town":"Cranberry Township",
      "county":"Butler County",
      "state":"Pennsylvania",
      "postcode":"16066",
      "country":"United States",
      "country_code":"us"
   },
   "namedetails":{
      "name":"Cranberry Township",
      "name:en":"Cranberry Township",
      "official_name":"Cranberry Township"
   }
}
Country Name: United States