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]+" ");
 }
 }
}

  

原文地址:https://www.cnblogs.com/E-star/p/3671014.html