Pinyin4j将汉字转换为拼音

package com.anyitzy.publish.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtil {
 public static String nameToPinyin(String chines) {
  if(chines==null || "".equals(chines)){
   return "";
  }else{
   String pinyinName = "";
   char[] nameChar = chines.replaceAll("[^\u4E00-\u9FA5|\\d|\\w]+", "").toCharArray();
   HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
   defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
   defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
   for (int i = 0; i < nameChar.length; i++) {
    if (nameChar[i] > 128) {
     try {
      
      pinyinName += PinyinHelper.toHanyuPinyinStringArray(
        nameChar[i], defaultFormat)[0].charAt(0);
     } catch (BadHanyuPinyinOutputFormatCombination e) {
      e.printStackTrace();
     }
    } else {
     pinyinName += nameChar[i];
    }
   }
   return pinyinName;
  }
  
 }

 public static String regexReplace(String str){ 
   // 只允许字母和数字       
        // String    regEx   =   "[^a-zA-Z0-9]";                     
           // 清除掉所有特殊字符  
     String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";  
     Pattern    p    =    Pattern.compile(regEx);     
     Matcher    m    =    p.matcher(str);
     m.find();
    return    m.replaceAll("").trim();     

     } 

 

 


 public static void main(String[] args) {
  //String content = "规*规范";
  //System.out.println(regexReplace(content));
  //String content = "法律、法12QQ-规类";
  //System.out.println(content.replaceAll("[^\u4E00-\u9FA5|\\d|\\w]+", ""));
 }
}

你可能感兴趣的:(Pinyin4j将汉字转换为拼音)