具有适当复数的Java国际化(i18n)

Dr.*_*ibo 33 java internationalization messageformat plural

我打算使用Java的标准i18n系统和复数形式的ChoiceFormat类,但后来意识到它不能处理某些语言的复杂多元规则(例如波兰语).如果它只处理类似英语的语言,那么它似乎有点无意义.

有什么选择来实现正确的复数形式?使用它们的利弊是什么?

Paw*_*yda 40

好吧,你已经正确标记了这个问题,所以我假设你对ICU有所了解.

使用ICU,您有两种选择来正确处理复数形式:

哪一个使用?就个人而言,我更喜欢直接使用PluralRules,从资源包中选择适当的消息.

ULocale uLocale = ULocale.forLanguageTag("pl-PL");
ResourceBundle resources = ResourceBundle.getBundle( "path.to.messages",
                               uLocale.toLocale());
PluralRules pluralRules = PluralRules.forLocale(uLocale);

double[] numbers = { 0, 1, 1.5, 2, 2.5, 3, 4, 5, 5.5, 11, 12, 23 };
for (double number : numbers) { 
  String resourceKey = "some.message.plural_form." + pluralRules.select(number);
  String message = "!" + resourceKey + "!";
  try {
    message = resources.getString(resourceKey);
    System.out.println(format(message, uLocale, number));
   } catch (MissingResourceException e) { // Log this } 
}
Run Code Online (Sandbox Code Playgroud)

当然,您(或翻译者)需要将正确的表单添加到属性文件中,在此示例中,我们说:

some.message.plural_form.one=Znaleziono {0} plik
some.message.plural_form.few=Znaleziono {0} pliki
some.message.plural_form.many=Znaleziono {0} plików
some.message.plural_form.other=Znaleziono {0} pliku
Run Code Online (Sandbox Code Playgroud)

对于其他语言(即阿拉伯语),您可能还需要使用"零"和"两个"关键字,有关详细信息,请参阅CLDR的语言复数规则.

或者,您可以使用PluralFormat选择有效的表单.通常的例子显示直接实例化,在我看来完全没有意义.使用ICU的MessageFormat更容易:

String pattern = "Znaleziono {0,plural,one{# plik}" +
                 "few{# pliki}" +
                 "many{# plików}" +
                 "other{# pliku}}";
MessageFormat fmt = new MessageFormat(pattern, ULocale.forLanguageTag("pl-PL"));
StringBuffer result = new StringBuffer();
FieldPosition zero = new FieldPosition(0);
double[] theNumber = { number };
fmt.format(theNumber, result, zero);
Run Code Online (Sandbox Code Playgroud)

当然,实际上你不会硬编码模式字符串,但在属性文件中放置这样的东西:

some.message.pattern=Found {0,plural,one{# file}other{# files}}
Run Code Online (Sandbox Code Playgroud)

这种方法的唯一问题是,翻译者必须知道占位符格式.我试图在上面的代码中展示的另一个问题是,MessageFormat的静态格式()方法(易于使用的方法)总是为默认的Locale格式化.这可能是Web应用程序中的一个真正问题,其中默认Locale通常表示服务器的一个.因此,我必须格式化特定的Locale(浮点数,请注意),代码看起来相当难看......

我仍然更喜欢PluralRules方法,这对我来说更清晰(虽然它需要使用相同的消息格式化样式,只能用辅助方法包装).