convert translated country-names to alpha2 with pycountry and gettext

最后都变了- 提交于 2020-01-15 03:44:16

问题


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 each country.

My current approach:

user_input = "France"
country_code = pycountry.countries.get(name=user_input).alpha2 # u'FR'

this works fine if the user input is made in English. Since the data is shown in the users preferred language, she will expect to search for it in her preferred language as well.

By using gettext with pycountry's locales I'm able to show the country-names in the users preferred language:

# example for a German user
gettext.translation('iso3166', pycountry.LOCALES_DIR, languages=['de']).install()
country_code = 'FR'
country = _(pycountry.countries.get(alpha2=country_code).name) # 'Frankreich'

now I'm searching for a way to translate the users input back to english (assume there are no typos) and fetch the country code from it:

user_input = "Frankreich"
translated_user_input = ??? # 'France'
country_code = pycountry.countries.get(name=translated_user_input).alpha2 # u'FR'

Has anyone a good idea, how to achieve this? Ideally by only using gettext and pycountry?


回答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'


来源:https://stackoverflow.com/questions/35434578/convert-translated-country-names-to-alpha2-with-pycountry-and-gettext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!