PinyinUtil.java 1.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
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<Pinyin> 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<Pinyin> pinyins = PinyinDictionary.convertToPinyin(chineseStr);
        if (CollectionUtils.isEmpty(pinyins)) {
            return StringUtils.EMPTY;
        }
        return String.valueOf(pinyins.get(0).getPinyinWithoutTone().charAt(0));
    }
}