Skip to content

Instantly share code, notes, and snippets.

@josefdlange
Created June 24, 2016 19:38
Show Gist options
  • Select an option

  • Save josefdlange/f7535ab6a24ca93b6f8da28d6a9cdc87 to your computer and use it in GitHub Desktop.

Select an option

Save josefdlange/f7535ab6a24ca93b6f8da28d6a9cdc87 to your computer and use it in GitHub Desktop.
Naive Country ISO3166 Alpha2 Resolver/Guesser
import difflib
import pycountry
def baseline_country(country_input, default="US"):
"""
Given a string input, return a two-character ISO3166 code.
"""
try:
if country_input and len(country_input) > 0:
if len(country_input) == 3: # Let's find the alpha2 for this probably-alpha3. Are there 3-letter countries?
matches = [c for c in pycountry.countries if c.alpha3.upper() == country_input.upper()]
if len(matches):
return matches[0].alpha2
elif len(country_input) == 2: # It's probably already an alpha2.
matches = [c for c in pycountry.countries if c.alpha2.upper() == country_input.upper()]
if len(matches):
return matches[0].alpha2
# If neither above condition finds a match, try a difflib string guess.
countries = [c for c in pycountry.countries]
names = [c.name.lower() for c in countries]
matching_name = difflib.get_close_matches(country_input, names)[0] # Could throw IndexError, but we handle it.
country = [c for c in countries if c.name.lower() == matching_name][0] # Could throw IndexError, but we handle it.
return country.alpha2
else:
return default
except Exception as e:
return default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment