Skip to main content
 首页 » 编程设计

python之使用 pycountry 和 gettext 将翻译后的国家名称转换为 alpha2

2024年10月24日11三少

我试图让我的用户按国家/地区搜索数据。用户将以他们的母语输入国家名称。 但是,我的数据库只包含每个国家/地区的 alpha2 代码。

我目前的做法:

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

如果用户输入的是英文,这就可以正常工作。由于数据以用户首选语言显示,因此她也希望以她的首选语言搜索它。

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

# 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' 

现在我正在寻找一种方法将用户输入的内容翻译回英语(假设没有拼写错误)并从中获取国家/地区代码:

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

有没有人有好主意,如何实现?理想情况下仅使用 gettext 和 pycountry?

请您参考如下方法:

我找到了一个解决方案,它可能没有完全优化性能,但可以工作并且不太难看:

user_input = "Frankreich" 
country_code = ''.join([country.alpha2 for country in pycountry.countries if _(country.name) == user_input]) # u'FR'