当前位置: 首页 > 工具软件 > JPinyin > 使用案例 >

JPinYin的简单使用

孔和畅
2023-12-01

JPinyin是一个汉字转拼音的Java开源类库,在PinYin4j的功能基础上做了一些改进。

1.在项目中导入依赖
  <dependency>
        <groupId>com.github.stuxuhai</groupId>
        <artifactId>jpinyin</artifactId>
        <version>1.1.7</version>
    </dependency>
2.简单使用

2.1 汉字转拼音

try {
            String str = "你好世界";
            //设置声调表示格式
            System.out.println(PinyinHelper.convertToPinyinString(str, ",", PinyinFormat.WITH_TONE_MARK)); // nǐ,hǎo,shì,jiè
            //数字表示声调
            System.out.println(PinyinHelper.convertToPinyinString(str, ",", PinyinFormat.WITH_TONE_NUMBER)); // ni3,hao3,shi4,jie4
            //无声调
            System.out.println( PinyinHelper.convertToPinyinString(str, ",", PinyinFormat.WITHOUT_TONE)); // ni,hao,shi,jie
            //获取拼音首字母
            System.out.println(PinyinHelper.getShortPinyin(str)); // nhsj
            //判断是否多音字
            System.out.println(PinyinHelper.hasMultiPinyin('啊'));//true
        } catch (PinyinException e) {
            e.printStackTrace();
        }
    }

2.2 繁体中文互转

 try {
            //简体转繁体
            char traditionalChinese = ChineseHelper.convertToTraditionalChinese('龙');
            //繁体转简体
            char simplifiedChinese = ChineseHelper.convertToSimplifiedChinese('龍');
            System.out.println(traditionalChinese);
            System.out.println(simplifiedChinese);
            //判断是否是汉字
            System.out.println(ChineseHelper.isChinese('龍'));//true
        } catch (Exception e) {
            e.printStackTrace();
        }

2.3 还有一个在项目中的应用(片段)

               //设置简码和城市简码
                String province = bcRegion.getProvince();
                String city = bcRegion.getCity();
                String district = bcRegion.getDistrict();

                province=province.substring(0,province.length()-1);
                city=city.substring(0,city.length()-1);
                district=district.substring(0,district.length()-1);

                bcRegion.setCitycode(PinyinHelper.convertToPinyinString(city,"",PinyinFormat.WITHOUT_TONE));//城市简码 taiyuan
                bcRegion.setShortcode(PinyinHelper.getShortPinyin(province+city+district)); //简码 sdhzcx
                bcRegions.add(bcRegion);
 类似资料: