Convert Translated Country-names To Alpha2 With Pycountry And Gettext
I'm trying to let my users search for data by country. The users will type in the country name in their native languages. However my database only contains the alpha2 codes for eac
Solution 1:
I found a solution, which might not be exactly performance optimized, but works and is not too ugly:
user_input = "Frankreich"
country_code = ''.join([country.alpha2 for country in pycountry.countries if _(country.name) == user_input]) # u'FR'
Solution 2:
Here is my solution, there is a lot to improve regarding performance, but it is working. the input is
- country name in some language
- language identifier in pycountry
import pycountry
import gettext
def map_country_code(self, country_name, language):
try:
# todo: when languages = en the program fails!
# todo: this methode takes to much time, is it o(n2) have to think on a better system+
if country_name is None:
return None
german = gettext.translation('iso3166', pycountry.LOCALES_DIR, languages=[language])
german.install()
_ = german.gettext
for english_country in pycountry.countries:
country_name = country_name.lower()
german_country = _(english_country.name).lower()
if german_country == country_name:
return english_country.alpha_3
except Exception as e:
self.log.error(e, exc_info=True)
return False
Solution 3:
It seems like gettext doesn't have a native support (!?) to reverse the translation (I really hope I am wrong about this, it seems like a normal functionality).
My solution is to create a new gettext object and switch the translation around. All the translation objects are found in the ._catalog dictionary. So I swap the keys for the entries.
import pycountry
import gettext
import copy
eng_to_german = gettext.translation('iso3166', pycountry.LOCALES_DIR,languages=['de'])
eng_to_german.install()
german_to_eng = copy.copy(eng_to_german) #Make a copy
german_to_eng._catalog = {} #Remove the catalog
for key in eng_to_german._catalog.keys():
german_to_eng._catalog[eng_to_german._catalog[key]] = key #replace the key with the entry and vice versa
#Verify
_ = german_to_eng.gettext
translated_string = _("Frankreich")
print(translated_string) #This should print "France"
Hope this helps!
Post a Comment for "Convert Translated Country-names To Alpha2 With Pycountry And Gettext"