能否通过pgeocode以国家名称或邮政编码获取国家代码?
Great question! Let's walk through how pgeocode works and what's possible here:
Core Limitation of pgeocode's Initialization
First, it's important to note that pgeocode requires a 2-letter ISO country code (like 'fr' for France) to initialize the Nominatim instance. This is because the library loads localized postal code datasets per country under the hood—there's no built-in support for using full country names (e.g., "France") directly in the initialization step.
Using Postal Codes to Automatically Detect Country
Unfortunately, pgeocode doesn't support auto-detecting the country from a standalone postal code either. Postal code formats vary wildly across countries (some are numeric, some alphanumeric, some have different lengths), so the library can't reliably map a single postal code to its corresponding country without prior context.
Workarounds to Achieve Your Goal
If you need to use country names or postal codes to get the right pgeocode instance, here are two practical workarounds:
Map country names to ISO codes manually
Create a simple dictionary to translate full country names to their 2-letter codes, then use that to initializeNominatim:import pgeocode country_mapping = { "France": "fr", "Germany": "de", "United States": "us", # Add more countries as needed } # Initialize using a country name target_country = "France" nomi = pgeocode.Nominatim(country_mapping[target_country]) print(nomi.query_postal_code("75013"))Use a third-party tool to get country code from a postal code
If you only have a postal code, use a general-purpose geocoding tool to first look up the country associated with the postal code, then use that country code to initialize pgeocode.
Recap of Your Example
Your original example is the correct, intended usage of pgeocode:
import pgeocode
nomi = pgeocode.Nominatim('fr')
nomi.query_postal_code("75013")
This works because you've explicitly told pgeocode to use France's postal code dataset before querying.
内容的提问来源于stack exchange,提问作者fadingbeat

