java把中文转为拼音的工具类

java | 2019-09-13 10:02:39

java把中文转为拼音的类


import net.sourceforge.pinyin4j.*;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
public class Pinyin
{
         public static void main(String[] args)
         {       
                   Hanyu hanyu = new Hanyu();
                   String str = "我们";
                   String strPinyin = hanyu.getStringPinYin(str);
                   System.out.println(strPinyin);
         }
}

class Hanyu
{
private HanyuPinyinOutputFormat format = null;
        private String[] pinyin;
        public Hanyu()
         {
                   format = new HanyuPinyinOutputFormat();                  
                   //WITH_TONE_NUMBER是输出拼音的音调 
                  //WITHOUT_TONE 是没有输出音调
                   format.setToneType(HanyuPinyinToneType.WITH_TONE_NUMBER);
                  // format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);                
                   pinyin = null;
         }
         //转换单个字符
         public String getCharacterPinYin(char c)
         {
               try
                {
                            pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
             }
                  catch(BadHanyuPinyinOutputFormatCombination e)
                   {
                            e.printStackTrace();
                   }
                   // 如果c不是汉字,toHanyuPinyinStringArray会返回null
                   if(pinyin == null) return null;
                   // 只取一个发音,如果是多音字,仅取第一个发音
                   return pinyin[0];   
         }
      //转换一个字符串
         public String getStringPinYin(String str)
         {
                   StringBuilder sb = new StringBuilder();
                   String tempPinyin = null;
                   for(int i = 0; i < str.length(); ++i)
                   {
                            tempPinyin =getCharacterPinYin(str.charAt(i));
                            if(tempPinyin == null)
                            {
                                     // 如果str.charAt(i)非汉字,则保持原样
                                     sb.append(str.charAt(i));
                            }
                            else
                            {
                                     sb.append(tempPinyin);
                            }
                   }
                   return sb.toString();
         }
}


登录后即可回复 登录 | 注册
    
关注编程学问公众号