package com.kwan.springbootkwan.utils; import com.hankcs.hanlp.dictionary.py.Pinyin; import com.hankcs.hanlp.dictionary.py.PinyinDictionary; import org.apache.commons.lang3.StringUtils; import org.springframework.util.CollectionUtils; import java.util.List; /** * 拼音工具类 * * @author : qinyingjie * @version : 2.2.0 * @date : 2023/8/26 11:16 */ public class PinyinUtil { /** * 获取中文完整拼音 * * @param chineseStr * @return */ public static String getPinyin(String chineseStr) { List pinyins = PinyinDictionary.convertToPinyin(chineseStr); StringBuilder stringBuilder = new StringBuilder(); for (Pinyin pinyin : pinyins) { stringBuilder.append(pinyin.getPinyinWithoutTone()); } return stringBuilder.toString(); } /** * 获取中文拼音首字母 * * @param chineseStr * @return */ public static String getInitial(String chineseStr) { List pinyins = PinyinDictionary.convertToPinyin(chineseStr); if (CollectionUtils.isEmpty(pinyins)) { return StringUtils.EMPTY; } return String.valueOf(pinyins.get(0).getPinyinWithoutTone().charAt(0)); } }