使用pycountry和gettext将转换后的国家/地区名称转换为alpha2 [英] convert translated country-names to alpha2 with pycountry and gettext

查看:145
本文介绍了使用pycountry和gettext将转换后的国家/地区名称转换为alpha2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让我的用户按国家/地区搜索数据.用户将使用其母语输入国家/地区名称. 但是我的数据库只包含每个国家/地区的alpha2代码.

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.

我目前的做法:

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.

通过将gettext与pycountry的语言环境结合使用,我可以用用户首选的语言显示国家/地区名称:

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'

任何人都有一个好主意,如何实现这一目标?理想情况下,仅使用gettext和pycountry?

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

推荐答案

我找到了一个解决方案,该解决方案可能并非完全针对性能进行了优化,但是可以正常工作并且不太难看:

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'

这篇关于使用pycountry和gettext将转换后的国家/地区名称转换为alpha2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆