gpt4 book ai didi

java - 将小数点 1 到 10 替换为名称 ("one", "two"..)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:57 25 4
gpt4 key购买 nike

我试图获取一个字符串,然后返回一个字符串,其中数字 1 到 10 替换为这些数字的单词。例如:

I won 7 of the 10 games and received 30 dollars.

应该变成:

I won seven of the ten games and received 30 dollars.

所以我这样做了:

import org.apache.commons.lang3.StringUtils;

String[] numbers = new String[] {"1", "2", "3","4","5","6","7","8","9","10"};
String[] words = new String[]{"one", "two", "three","four","five","six",
"seven","eight","nine","ten"};
System.out.print(StringUtils.replaceEach(phrase, numbers, words));

结果是这样的:

I won seven of the one0 games and received three0 dollars.

所以我尝试了一种蛮力方式,我确信可以通过正则表达式或更优雅的字符串操作来改进它:

public class StringReplace {

public static void main(String[] args) {
String phrase = "I won 7 of the 10 games and received 30 dollars.";
String[] sentenceWords = phrase.split(" ");
StringBuilder sb = new StringBuilder();
for (String s: sentenceWords) {
if (isNumeric(s)) {
sb.append(switchOutText(s));
}

else {
sb.append(s);
}
sb.append(" ");

}
System.out.print(sb.toString());
}

public static String switchOutText(String s) {
if (s.equals("1"))
return "one";
else if (s.equals("2"))
return "two";
else if (s.equals("3"))
return "three";
else if (s.equals("4"))
return "four";
else if (s.equals("5"))
return "fivee";
else if (s.equals("6"))
return "six";
else if (s.equals("7"))
return "seven";
else if (s.equals("8"))
return "eight";
else if (s.equals("9"))
return "nine";
else if (s.equals("10"))
return "ten";
else
return s;
}

public static boolean isNumeric(String s) {
try {
int i = Integer.parseInt(s);
}
catch(NumberFormatException nfe) {
return false;
}
return true;
}

}

有没有更好的办法?对正则表达式建议特别感兴趣。

最佳答案

这种方法使用正则表达式来匹配被非数字包围的目标数字(或开始或结束字符):

String[] words = { "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten" };
String phrase = "I won 7 of the 10 games and received 30 dollars.";

for (int i = 1; i <= 10; i++) {
String pattern = "(^|\\D)" + i + "(\\D|$)";
phrase = phrase.replaceAll(pattern, "$1" + words[i - 1] + "$2");
}

System.out.println(phrase);

这打印:

I won seven of the ten games and received 30 dollars.

如果数字是句子中的第一个或最后一个单词,它也会处理。例如:

9 cats turned on 100 others and killed 10

正确翻译成

nine cats turned on 100 others and killed ten

关于java - 将小数点 1 到 10 替换为名称 ("one", "two"..),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21094049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com