Как конвертировать слова в числа в Java с помощью icu4j - PullRequest
0 голосов
/ 27 мая 2019

Я хочу разобрать слова в числа и получить ошибку, когда строка не полностью выражает действительное число, например:

"Twenty two" => 22
"One hundred forty four" => 144
"Twenty bla bla" => error
"One hundred forty thousand one" => error

Я пытался использовать com.ibm.icu.text.RuleBasedNumberFormat, но метод parse() анализирует только начало, а не полную строку. Это упоминается в их javadoc:
Анализирует текст с начала данной строки для получения числа. Метод может не использовать весь текст данной строки

В их javadoc упоминается, что можно использовать специальный набор правил в сочетании с RuleBasedCollator для изменения снисходительного разбора, но я изо всех сил пытаюсь достичь этого.

public class NumFormatter {
    public static int numberFromString(String number, Locale locale) {
        RuleBasedNumberFormat numberFormat = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);

        try {
            return numberFormat.parse(number).intValue();
        } catch (ParseException e) {
            return -1;
        }
    }
}

public class NumFormatterTest
    @Test
    public void formatNumber_fromString() {
        Locale locale =  new Locale("en");
        assertEquals(numberFromString("twenty two", locale), 22);
        assertEquals(numberFromString("three blablabla ", locale), -1); // not ok. It return 3 and not -1.
    }
}

pom.xml
<dependency>
    <groupId>com.ibm.icu</groupId>
    <artifactId>icu4j</artifactId>
    <version>60.2</version>
</dependency>

Кто-нибудь должен был иметь дело с этим раньше? Заранее спасибо.

Ссылки

1 Ответ

0 голосов
/ 27 мая 2019
  • Содержание документа выглядит следующим образом:
To see how these rules actually work in practice, consider the following example: Formatting 25,430 with this rule set would work like this:

<< thousand >>  [the rule whose base value is 1,000 is applicable to 25,340]
twenty->> thousand >>   [25,340 over 1,000 is 25. The rule for 20 applies.]
twenty-five thousand >> [25 mod 10 is 5. The rule for 5 is "five."
twenty-five thousand << hundred >>  [25,340 mod 1,000 is 340. The rule for 100 applies.]
twenty-five thousand three hundred >>   [340 over 100 is 3. The rule for 3 is "three."]
twenty-five thousand three hundred forty    [340 mod 100 is 40. The rule for 40 applies. Since 40 divides evenly by 10, the hyphen and substitution in the brackets are omitted.]

public class NumberFormat {

    public static void main(String[] args) {
        Locale locale = new Locale("en");
        int twenty = numberFromString("twenty-two", locale);
        System.out.println(twenty);
    }

    public static int numberFromString(String number, Locale locale) {
        RuleBasedNumberFormat numberFormat = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);

        try {
            return numberFormat.parse(number).intValue();
        } catch (ParseException e) {
            return -1;
        }
    }
}

Вам необходимо заменить пробелы на -

...