Skip to content

Instantly share code, notes, and snippets.

@jpmckinney
Last active December 2, 2021 00:11
Show Gist options
  • Save jpmckinney/950006f83e2f04db81de5617865b43dd to your computer and use it in GitHub Desktop.
Save jpmckinney/950006f83e2f04db81de5617865b43dd to your computer and use it in GitHub Desktop.
Renames flags from Flaticon to use ISO 3166-1 alpha 2 codes.
import os
import sys
from hdx.location.country import Country
# https://www.flaticon.com/packs/rectangular-country-simple-flags?word=flags
FLAG_PATH = 'path/to/flaticon/folder'
excluded = {
# Non-ISO states with limited recognition
'162-somaliland',
'215-northen-cyprus',
# Non-sovereign states that collide when fuzzy matching
'109-bonaire', # BQ Bonaire, Sint Eustatius and Saba
'166-sint-eustatius', # BQ Bonaire, Sint Eustatius and Saba
'168-saba-island', # BQ Bonaire, Sint Eustatius and Saba
'112-british-virgin-islands', # VG Virgin Islands (British)
'188-virgin-islands', # VI Virgin Islands (U.S.)
# Subnational divisions that collide when fuzzy matching
'123-british-columbia', # collides with VG
}
renamed = {}
no_flag = {}
for root, dirs, files in os.walk(FLAG_PATH):
for file in files:
source = os.path.join(root, file)
basename, extension = os.path.splitext(file)
if basename in excluded or not extension or not basename[:3].isdigit():
continue
query = basename[4:].replace('-', ' ')
iso3 = Country.get_iso3_country_code_fuzzy(query)[0]
if not iso3:
no_flag[basename] = query
continue
iso2 = Country.get_country_info_from_iso3(iso3)['#country+code+v_iso2']
destination = os.path.join(root, f'{iso2}{extension}')
if os.path.exists(destination):
print(f'{source}: {renamed[destination]} already renamed to {destination}, add to `excluded`?', file=sys.stderr)
continue
os.rename(source, destination)
renamed[destination] = source
for basename, query in no_flag.items():
print(f'{basename}: no country matching "{query}"', file=sys.stderr)
@hpop
Copy link

hpop commented Aug 23, 2021

Thank you soo much! ❤️

@SametSahin10
Copy link

SametSahin10 commented Dec 2, 2021

Thanks! hdx-python-country needs to be installed before running the code. Run the command below to install it.

pip install hdx-python-country

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment