获取中文拼音首字母

获取中文词语拼音首字母,如 中华人民共和国 -> zhrmghg

Maven坐标

<dependency>
    <groupId>com.hankcs</groupId>
    <artifactId>hanlp</artifactId>
    <version>portable-1.7.8</version>
</dependency>
 
Java代码如下
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.dictionary.py.Pinyin;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Pattern;

/**
 * 获取中文拼音首字母
 *
 * @author
 */
public class LanguageTreatUtils {
    public LanguageTreatUtils() {
    }
    public static String getPinyin(String text) {
        StringBuffer buffer = new StringBuffer();
        if (StringUtils.isNotBlank(text)) {
            for (int i = 0; i < text.length(); ++i) {
                String subStr = text.substring(i, i + 1);
                if (Pattern.matches("[一-龥]", subStr)) {
                    buffer.append(((Pinyin) HanLP.convertToPinyinList(subStr).get(0)).getFirstChar());
                } else {
                    buffer.append(subStr);
                }
            }
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        String str = "中华人民共和国";
        System.out.println(getPinyin(str));
    }
}

 

posted @ 2022-03-15 15:30  YF721  阅读(131)  评论(0编辑  收藏  举报