java漢字轉拼音工具類分享,java漢字拼音工具類

來源:互聯網
上載者:User

java漢字轉拼音工具類分享,java漢字拼音工具類

本文執行個體為大家分享了java漢字轉拼音工具類的具體代碼,供大家參考,具體內容如下

import com.google.common.base.Strings;import net.sourceforge.pinyin4j.PinyinHelper;import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.util.ArrayList;import java.util.List;import java.util.Locale;import java.util.TreeSet;public class PinyinUtils {  private static final Logger logger = LoggerFactory.getLogger(PinyinUtils.class);  /**   * 單字解析   *   * @param str first   * @return   */  public static String[] convert(String str) {    String[] reslut = null;    HanyuPinyinOutputFormat hanyuPinyinOutputFormat = new HanyuPinyinOutputFormat();    hanyuPinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);    try {      reslut = PinyinHelper.toHanyuPinyinStringArray(str.charAt(0), hanyuPinyinOutputFormat);      TreeSet<String> stringTreeSet = new TreeSet<>();      for (int i = 0; i < reslut.length; i++) {        if(reslut.length >=3) {          break;        }        stringTreeSet.add(reslut[i].replace("u:","v"));      }      reslut = new String[stringTreeSet.size()];      reslut = stringTreeSet.toArray(reslut);    } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {      badHanyuPinyinOutputFormatCombination.printStackTrace();    } catch (Exception e) {      logger.error("[convert]: ", e);    }    return reslut;  }  /**   * 片語解析(全寫)   *   * @param chs   * @return   */  public static String getSelling(String chs) {    return translate(chs, false);  }  /**   * 漢字轉拼音   *   * @param chs   * @param acronym   * @return   */  private static String translate(String chs, boolean acronym) {    StringBuffer buffer=new StringBuffer();    if (Strings.isNullOrEmpty(chs))      return "";    try {      List<List<String>> temps = new ArrayList<>();      int len = chs.length();      int len1 = 0;      for (int i = 0; i < len; i++) {        List<String> stringList = new ArrayList<>();        String key = chs.charAt(i) + "";        if (key.getBytes().length >= 2) {          String[] temp = convert(key);          if(temp.length == 0) {            continue;          }          if (temp == null) {            stringList.add("");          } else {            for (String v : temp) {              stringList.add(v);            }          }        } else {          stringList.add(key);        }        temps.add(stringList);        len1++;      }      List<List<String>> t = new ArrayList<>();      for (int i = 0; i < len1; i++) {        List<String> currentList = new ArrayList<>();        List<String> stringList = temps.get(i);        if (stringList != null) {          for (String s : stringList) {            if (acronym) {              s = s.charAt(0) + "";            }            if (i > 0) {              List<String> preList = t.get(i - 1);              if (preList != null) {                for (String s1 : preList) {                  currentList.add(s1 + s);                }              }            }else{              currentList.add(s);            }          }        }        t.add(i, currentList);      }      if (t.size()>0){        List<String> currentList= t.get(t.size()-1);        if (currentList!=null){          for(String current : currentList){            buffer.append(current);            buffer.append("");          }        }      }      return buffer.toString();    } catch (Exception e) {      logger.error("[getSortLetters]: ", e);      return "";    }  }  /**   * 片語解析(縮寫)   *   * @param chs   * @return   */  public static String getSmallSelling(String chs) {    return translate(chs, true);  }  /**   * 擷取首字母   *   * @return   */  public static String getSortLetters(String pingyin) {    try {      String sortString = pingyin.substring(0, 1).toUpperCase(Locale.getDefault());      // Regex,判斷首字母是否是英文字母      if (sortString.matches("[A-Z]")) {        return sortString.toUpperCase(Locale.getDefault());      }    } catch (Exception e) {      logger.error("[getSortLetters]: ", e);    }    return "#";  }  public static void main(String [] args) {    PinyinUtils p = new PinyinUtils();    System.out.println(p.getSelling("單個"));    System.out.println(p.getSmallSelling("測試"));  }}

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.