使用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

你可能感兴趣的:(pinyin4j)