This article describes the method of Java to convert Chinese characters into Chinese pinyin. Share it for your reference, as follows:
I was wandering around the Internet and accidentally saw a very interesting gadget called pinyin4j. It can convert Chinese characters into Chinese pinyin. Using his words and combined with lucene and Chinese participle, you can create a function similar to Google to input Chinese pinyin for full text search. The implemented code is as follows
package pinyin4j;import net.sourceforge.pinyin4j.PinyinHelper;import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;public class pinyin4jTest { public static void main(String argsp[]) { try { String output = pinyin4jTest.CNToPinyin("Hello with you", null); System.out.println(output); } catch (BadHanyuPinyinOutputFormatCombination e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * @parm inputCN Chinese string input* @parm seg Delimiter when outputting Chinese pinyin* * HanyuPinyinOutputFormat provides several output modes* HanyuPinyinCaseType: Set whether the result of the input is uppercase or lowercase English LOWERCASE: lowercase UPPERCASE: uppercase * HanyuPinyinToneType: whether the output indicates the tone and the accent WITH_TONE_NUMBER: indicates the tone such as YE1 1-4, which means 1-4 sound* WITHOUT_TONE: The tone symbol is not displayed HanyuPinyinVCharType: What kind of pinyin encoding should be used for the output*/ public static String CNToPinyin(String inputCN, String seg) throws BadHanyuPinyinOutputFormatCombination { char[] inputArray = inputCN.toCharArray(); if (seg == null) seg = " "; HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); format.setCaseType(HanyuPinyinCaseType.LOWERCASE); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); format.setVCharType(HanyuPinyinVCharType.WITH_V); String output = ""; String[] temp = new String[10]; for (int i = 0; i < inputArray.length; i++) { temp = PinyinHelper.toHanyuPinyinStringArray(inputArray[i], format); //If the entered Chinese character is a polyphonic character, different pronunciations will be placed into temp[] in sequence. If it is not a polyphonic character, only the value in temp[0] is for (int j = 0; j < temp.length; j++) { output += temp[j] + seg; } } return output; }}I hope this article will be helpful to everyone's Java programming.