Java 汉字转拼音

2022-08-24 08:36:42 浏览数 (1)

需求背景

因为用户前台输入的是汉字, 但是在创建图数据库的Tag节点的时候, 虽然能用中文, 但是我觉得还是不要用了, 就像是Java也能定义中文的类和字段一样奇怪, 但是又没有翻译API, 也可能又网络的问题, 综合考虑, 可以直接转为汉字拼音

添加POM依赖

代码语言:javascript复制
<!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->
<dependency>
  <groupId>com.belerweb</groupId>
  <artifactId>pinyin4j</artifactId>
  <version>2.5.1</version>
</dependency>

代码

代码语言:javascript复制
package com.jd.knowledgeextractionplatform.utils;
 
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
 
/**
 * 汉字转换为拼音
 */
public class ChineseConvertToPinyin {
    /**
     * 测试main方法
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("‘张三’首字母大写:"   toFirstChar("张三").toUpperCase()); //转为首字母大写
        System.out.println("‘张三’转成拼音:"   toPinyin("张三"));
    }
    /**
     * 获取字符串拼音的第一个字母
     */
    public static String toFirstChar(String chinese){
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();  //转为单个字符
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i  ) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr  = PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else{
                pinyinStr  = newChar[i];
            }
        }
        return pinyinStr;
    }
 
    /**
     * 汉字转为拼音
     */
    public static String toPinyin(String chinese){
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i  ) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr  = PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else{
                pinyinStr  = newChar[i];
            }
        }
        return pinyinStr;
    }
}

效果

0 人点赞