How to get the language name in native language?

烂漫一生 提交于 2019-12-23 10:57:25

问题


This is my first time using ICU API, and I'm having a very hard time trying to find out something that I assumed to be very simple: to get a given locale/language name in the native language (instead of in English)

Examples:

fr    -> Français
en    -> English
pt_BR -> Português Brasileiro, or "Português (Brasil)"
es_ES -> Español Iberico, or "Español (España)"

As a reference, in babel I can get a given locale name in any language, native being the default:

>>> import babel
>>> locale = babel.Locale.parse('pt_BR')
>>> locale.get_display_name()
português (Brasil)
>>> locale.get_display_name('fr')
portugais (Brésil)
>>> locale.get_display_name('en')
Portuguese (Brazil)

So, how to do the same in ICU? Examples in python are most welcome, since I'm using PyICU, but Java/C/C++ is fine too, since my problem is with the API, and not the language.

Thanks!


回答1:


I've just found out: the best method is getDisplayName(), but, instead of passing an string as argument, I must pass... a Locale instance!

The complete code goes like:

>>> import icu
>>> locale = icu.Locale("pt_BR")
>>> print icu.getDisplayName()
u'portuguese (Brazil)'
>>> print icu.getDisplayName(locale)
u'portugu\xeas (Brasil)'

So, unlike babel, Locale methods by default return names in the user's current locale. I must pass the instance itself to get name in native language. So it's easy if you want names in your language (in my case, English), but if I wanted in French, for example, I would have to create a new Locale instance of 'fr_FR'. Weird API, but still...




回答2:


There is a function getDisplayLanguage, which optionally takes the name of another locale. I don't know how the C-api translates to Python, but the relevant C docs are here.


Glancing over the PyICU-docs, it seems to be something like:

locale = Locale("pt_BR")
name = locale.getDisplayLanguage("en")

Looking at the wrapper source, it seems as if getDisplayLanguage takes a zero, one or two-tuple. What about getDisplayLanguage(("en",))? I'm not familiar with the PyICU-code base so I'm guessing here.




回答3:


#include <unicode/locid.h>
#include <unicode/ustream.h>
#include <iostream>

int main()
{
  Locale l("pt_BR");
  UnicodeString result;
  std::cout <<   l.getDisplayName(l, result) << std::endl;
}

português (Brasil)

I'm sorry you had trouble with the ICU API. Do you have any suggestion for clarification?



来源:https://stackoverflow.com/questions/10405915/how-to-get-the-language-name-in-native-language

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