我试图让我的用户按国家/地区搜索数据。用户将使用其母语键入国家/地区名称。 但是,我的数据库只包含每个国家/地区的alpha2代码。
我目前的做法:
user_input = "France"
country_code = pycountry.countries.get(name=user_input).alpha2 # u'FR'
如果用户输入是用英语制作的,这可以正常工作。由于数据以用户首选语言显示,因此她也希望以其首选语言搜索数据。
通过使用带有pycountry语言环境的gettext,我能够以用户首选语言显示国家/地区名称:
# 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?
答案 0 :(得分:2)
我找到了一个解决方案,它可能不是完全性能优化的,但是有效并且不太难看:
user_input = "Frankreich"
country_code = ''.join([country.alpha2 for country in pycountry.countries if _(country.name) == user_input]) # u'FR'
答案 1 :(得分:1)
这是我的解决方案,在性能方面有很多改进,但是可以使用。 输入是
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
答案 2 :(得分:0)
似乎 gettext 没有本地支持 (!?) 来反转翻译(我真的希望我错了,这似乎是正常功能)。
我的解决方案是创建一个新的 gettext 对象并切换翻译。所有翻译对象都可以在 ._catalog 字典中找到。所以我交换了条目的密钥。
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"
希望这会有所帮助!