• 使用pinyin4j实现汉字转拼音


    1. maven项目,请在pom.xml里边添加包依赖相关配置:

    1 <dependency>
    2     <groupId>net.sourceforge.pinyin4j</groupId>
    3     <artifactId>pinyin4j</artifactId>
    4     <version>2.5.0</version>
    5 </dependency>

    2.编写实例代码:

     1 /*
     2  * Copyright 2013 Alibaba.com All right reserved. This software is the
     3  * confidential and proprietary information of Alibaba.com ("Confidential
     4  * Information"). You shall not disclose such Confidential Information and shall
     5  * use it only in accordance with the terms of the license agreement you entered
     6  * into with Alibaba.com.
     7  */
     8 package com.yunos.tv.server.controller.web;
     9 
    10 
    11 import net.sourceforge.pinyin4j.PinyinHelper;
    12 import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
    13 import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
    14 import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
    15 import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
    16 
    17 import org.junit.Test;
    18 
    19 /**
    20  * 类PinyinTest.java的实现描述:TODO 类实现描述
    21  * @author riqi 2013-6-28 下午5:24:57
    22  */
    23 public class PinyinTest {
    24 
    25     @Test
    26     public void pinyinTest() {
    27 
    28         String input = "阿里巴巴";
    29         StringBuilder pinyin = new StringBuilder();
    30 
    31         for (int i = 0; i < input.length(); i++) {
    32             HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
    33             defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    34             defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
    35             char c = input.charAt(i);
    36             String[] pinyinArray = null;
    37             try {
    38                 pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat);
    39             } catch (BadHanyuPinyinOutputFormatCombination e) {
    40                 e.printStackTrace();
    41             }
    42             if (pinyinArray != null) {
    43                 pinyin.append(pinyinArray[0]);
    44             } else if (c != ' ') {
    45                 pinyin.append(input.charAt(i));
    46             }
    47         }
    48 
    49         System.out.println(pinyin.toString().trim().toLowerCase());
    50     }
    51 
    52 }

    3. 运行结果:alibaba

  • 相关阅读:
    CentOS 7中cAdvisor的安装过程
    怎么查看centos版本
    使docker命令不用加sudo的方法
    Linux进程相关函数system,fork,exec函数族的区别
    git pre-commit hook failed 解决办法
    lint-staged 教程
    用webpack将多个scss文件打包成一个css文件
    js连按键盘事件
    vscode快捷键
    vim 操作命令大全
  • 原文地址:https://www.cnblogs.com/liuriqi/p/4039222.html
Copyright © 2020-2023  润新知