pinyin 4 jを用いて漢字のピンインを変換する
7853 ワード
1.mavenプロジェクト、pom.xmlにパッケージ依存構成を追加してください:
2.インスタンスコードの作成:
3.運転結果:alibaba
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