java 解析漢字拼音
pinyin4j的使用很方便,一般轉換只需要使用PinyinHelper類的靜態工具方法即可:
String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(‘趙’);
//該類還有其他的拼音轉換形式,但是基本上用不到,就不介紹了
返回的數組即是該字符的拼音,如上例就是pinyin[0]=zhao,后面的數字代表聲調,聲調為5表示輕讀,無聲調。之所謂返回數組,是因為被判定的漢字有可能有多個讀音。如果輸入的參數不是漢字,則返回null。
拼音格式化
如果對于拼音轉換后的結果有一些特定的格式要求目前pinyin4j支持:
聲調格式化。例如:“劉”字的格式化后為“liu2”或“liu”或“liú”
對特殊拼音ü的的顯示格式。例如“u:”或“v”或“ü”
大小寫的轉換。例如:“liu2”或“LIU2”
以上這些格式可以混合使用,下面就來介紹具體的使用方法,首先需要創建格式化對象HanyuPinyinOutputFormat,例如:
HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
然后分別調用outputFormat的set方法設置上述一些格式要求:
設置聲調格式:
outputFormat.setToneType(HanyuPinyinToneType);
方法參數HanyuPinyinToneType有以下常量對象:
HanyuPinyinToneType.WITH_TONE_NUMBER 用數字表示聲調,例如:zhao4
HanyuPinyinToneType.WITHOUT_TONE 無聲調表示,例如:zhao
HanyuPinyinToneType.WITH_TONE_MARK 用聲調符號表示,例如:zhao
設置特殊拼音ü的顯示格式:
outputFormat.setVCharType(HanyuPinyinVCharType);
方法參數HanyuPinyinVCharType有以下常量對象:
HanyuPinyinVCharType.WITH_U_AND_COLON 以U和一個冒號表示該拼音,
HanyuPinyinVCharType.WITH_V 以V表示該字符,
HanyuPinyinVCharType.WITH_U_UNICODE
設置大小寫格式
outputFormat.setCaseType(HanyuPinyinCaseType);
HanyuPinyinCaseType.LOWERCASE 轉換后以全小寫方式輸出
HanyuPinyinCaseType.UPPERCASE 轉換后以全大寫方式輸出
設置好格式對象后還是利用上述的工具類方法進行拼音轉換,只不過需要將格式化對象當成方法參數傳入轉換方法,告知要轉換的格式要求:
String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(‘劉’, outputFormat);
但該方法會有異常拋出,注意處理。
public class Text { public static String[] Convert( char hz) { HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat(); outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); outputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE); outputFormat.setToneType(HanyuPinyinToneType.WITH_TONE_MARK); String[] Pinyin = null; try { Pinyin = PinyinHelper.toHanyuPinyinStringArray(hz,outputFormat); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } return Pinyin; } public static void main(String[] args) { String string = "我是中國人"; char str[] = string.toCharArray(); for(char s : str) { String[] string1 = Convert(s); System.out.print(string1[0]+" "); } } }
本文由用戶 zjbpku 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!