PinyinUtil.java 2.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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 {

    /**
20
     * 获取中文完整拼音-不带音标
21 22 23 24 25 26 27 28 29 30 31 32 33
     *
     * @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();
    }

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    /**
     * 获取中文完整拼音-指定分隔符
     *
     * @param chineseStr
     * @return
     */
    public static String getPinyin(String chineseStr, String separator) {
        List<Pinyin> pinyins = PinyinDictionary.convertToPinyin(chineseStr);
        StringBuilder stringBuilder = new StringBuilder();
        if (!CollectionUtils.isEmpty(pinyins)) {
            final int size = pinyins.size();
            for (int i = 0; i < size; i++) {
                if (i != 0 && i != size) {
                    stringBuilder.append(separator);
                }
                stringBuilder.append(pinyins.get(i).getPinyinWithoutTone());
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 带音标
     *
     * @param chineseStr
     * @return
     */
    public static String getPinyinWithToneMark(String chineseStr) {
        List<Pinyin> pinyins = PinyinDictionary.convertToPinyin(chineseStr);
        StringBuilder stringBuilder = new StringBuilder();
        for (Pinyin pinyin : pinyins) {
            stringBuilder.append(pinyin.getPinyinWithToneMark());
        }
        return stringBuilder.toString();
    }
69 70 71 72 73 74 75 76 77 78 79 80 81 82

    /**
     * 获取中文拼音首字母
     *
     * @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));
    }
83 84 85 86 87 88

    public static void main(String[] args) {
        System.out.println(PinyinUtil.getPinyin("秦英杰", "_"));
        System.out.println(PinyinUtil.getInitial("秦英杰"));
    }
}