您的位置:首页 > 其它

使用pinyin4j实现汉字转拼音

2014-10-20 23:31 351 查看
1. maven项目,请在pom.xml里边添加包依赖相关配置:

<dependency>
<groupId>net.sourceforge.pinyin4j</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>


2.编写实例代码:

/*
* Copyright 2013 Alibaba.com All right reserved. This software is the
* confidential and proprietary information of Alibaba.com ("Confidential
* Information"). You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement you entered
* into with Alibaba.com.
*/
package com.yunos.tv.server.controller.web;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.junit.Test;

/**
* 类PinyinTest.java的实现描述:TODO 类实现描述
* @author riqi 2013-6-28 下午5:24:57
*/
public class PinyinTest {

@Test
public void pinyinTest() {

String input = "阿里巴巴";
StringBuilder pinyin = new StringBuilder();

for (int i = 0; i < input.length(); i++) {
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
char c = input.charAt(i);
String[] pinyinArray = null;
try {
pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
if (pinyinArray != null) {
pinyin.append(pinyinArray[0]);
} else if (c != ' ') {
pinyin.append(input.charAt(i));
}
}

System.out.println(pinyin.toString().trim().toLowerCase());
}

}


3. 运行结果:alibaba
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: