1.引入jar包
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
<scope>compile</scope>
</dependency>
2.编写工具类(ChangeChinesePinyin.java)
package com.xxxx.cn.utill;
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.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @program:
* @description: 汉字转拼音
* @author:
* @create: 2022年3月26日
**/
public class ChangeChinesePinyin {
public static Map<String, String> changeChinesePinyin(String chinese) throws BadHanyuPinyinOutputFormatCombination {
Map<String, String> pinyin = new HashMap<String, String>();
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
StringBuffer fullPinyin = new StringBuffer();
StringBuffer simplePinyin = new StringBuffer();
StringBuffer firstPinyin = new StringBuffer();
char[] chineseChar = chinese.toCharArray();
for (int i = 0; i < chineseChar.length; i++) {
String[] str = null;
try {
str = PinyinHelper.toHanyuPinyinStringArray(chineseChar[i],
format);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
if (str != null) {
if (str.length == 0) {
continue;
}
fullPinyin = fullPinyin.append(str[0].toString());
simplePinyin = simplePinyin.append(str[0].charAt(0));
}
if (str == null) {
String regex = "^[0-9]*[a-zA-Z]*+$";
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(String.valueOf(chineseChar[i]));
if (m.find()) {
fullPinyin = fullPinyin.append(chineseChar[i]);
simplePinyin = simplePinyin.append(chineseChar[i]);
}
}
}
String[] name = PinyinHelper.toHanyuPinyinStringArray(chineseChar[0], format);
if(name == null && fullPinyin.substring(0,1).matches("[a-zA-Z]")){
name = new String[]{fullPinyin.substring(0,1)};
}else if (name == null){
name = new String[]{"#"};
}
firstPinyin = firstPinyin.append(name[0].charAt(0));
pinyin.put("fullPinyin", fullPinyin.toString());
pinyin.put("simplePinyin", simplePinyin.toString().toUpperCase());
pinyin.put("groupPinyin", firstPinyin.toString().toUpperCase());
return pinyin;
}
}
3.调用
public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
Map<String, String> fydmcPinYinMap = changeChinesePinyin("拼音");
System.out.println(fydmcPinYinMap.get("fullPinyin"));
String simplePinyin = fydmcPinYinMap.get("simplePinyin");
System.out.println(simplePinyin);
System.out.println(fydmcPinYinMap.get("groupPinyin"));
System.out.println(simplePinyin+":最终");
}
4.测试结果
pinyin
PY
P
PY:最终
|