中文转拼音工具类

该代码示例展示了如何使用pinyin4j库在Java中将汉字转换为全拼和首字母简拼,包括处理非汉字字符。尽管对多音字的支持不够精确,但适用于一般场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导入依赖

    <dependency>
        <groupId>com.belerweb</groupId>
        <artifactId>pinyin4j</artifactId>
        <version>2.5.1</version>
    </dependency>

使用

public class ConvertPinyinUtil {
    /**
     * 汉字转全拼
     *
     * @param str
     * @return
     * @throws Exception
     */
    public static String getPinyin(String str) throws Exception {
        if (str == null || str.length() == 0) {
            return "";
        }
        char[] t1 = null;
        t1 = str.toCharArray();
        String[] t2 = new String[t1.length];
		// 设置汉字拼音输出的格式
        HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
        t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 小写
        t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
        t3.setVCharType(HanyuPinyinVCharType.WITH_V);

        String t4 = "";
        int t0 = t1.length;
        try {
            for (int i = 0; i < t0; i++) {
				// 判断是否为汉字字符
                if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
					// 将汉字的几种全拼都存到t2数组中
                    t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
                    t4 += t2[0];// 取出该汉字全拼的第一种读音并连接到字符串t4后
                } else {
					// 如果不是汉字字符,直接取出字符并连接到字符串t4后
                    t4 += Character.toString(t1[i]);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            throw e;
        }
        return t4;
    }

    /**
     * 汉字转简拼
     *
     * @param str
     * @return String
     */
    public static String getPinYinHeadChar(String str) {
        String convert = "";
        if (str == null || str.length() == 0) {
            return convert;
        }
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            // 提取汉字的首字母
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert.toUpperCase();
    }

示例

public static void main(String[] arg0) throws Exception {
        String pinyin = getPinyin("好好学习,天天向上");
        System.out.println(pinyin);//输出haohaoxuexi,tiantianxiangshang
        String pinYinHeadChar = getPinYinHeadChar("好好学习,天天向上");
        System.out.println(pinYinHeadChar);//输出HHXX,TTXS
    }

该类基本满足日常使用,但是对多音字识别不是很准确,汉语博大精深

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值