汉字转拼音
Maven引用
<dependency><groupId>com.belerweb</groupId><artifactId>pinyin4j</artifactId><version>2.5.1</version></dependency>
Scala Demo:
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharTypeobject Test {def main(args: Array[String]): Unit = {println(getPinYin("大陆电视剧"))}def getPinYin(text :String): String ={val format = new HanyuPinyinOutputFormatformat.setCaseType(HanyuPinyinCaseType.LOWERCASE)format.setToneType(HanyuPinyinToneType.WITHOUT_TONE)format.setVCharType(HanyuPinyinVCharType.WITH_V)val input = text.trim.toCharArrayvar output:String = ""for( i <- 0 to input.length-1){import net.sourceforge.pinyin4j.PinyinHelperif (java.lang.Character.toString(input(i)).matches("[\\u4E00-\\u9FA5]+")) {val temp = PinyinHelper.toHanyuPinyinStringArray(input(i), format)output += temp(0) +" "}else output += java.lang.Character.toString(input(i))}output}
}
Java Demo
public static String getPingYin(String inputString) {HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();format.setCaseType(HanyuPinyinCaseType.LOWERCASE);format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);format.setVCharType(HanyuPinyinVCharType.WITH_V);String output = "";if (inputString != null && inputString.length() > 0&& !"null".equals(inputString)) {char[] input = inputString.trim().toCharArray();try {for (int i = 0; i < input.length; i++) {if (java.lang.Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);output += temp[0];} elseoutput += java.lang.Character.toString(input[i]);}} catch (BadHanyuPinyinOutputFormatCombination e) {e.printStackTrace();}} else {return "*";}return output;}