栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java实现将汉字转化为汉语拼音的方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java实现将汉字转化为汉语拼音的方法

本文实例讲述了Java实现将汉字转化为汉语拼音的方法。分享给大家供大家参考,具体如下:

网上乱转,偶然看到一个很有意思的小工具,名字叫pinyin4j,可以把汉字转换为汉语拼音,利用他的话再配合上lucene、中文分词就可以做出类似google那种输入汉语拼音进行全文检索的功能了。实现的代码如下

package pinyin4j;
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.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
public class pinyin4jTest {
  public static void main(String argsp[]) {
    try {
      String output = pinyin4jTest.CNToPinyin("你和你好", null);
      System.out.println(output);
    } catch (BadHanyuPinyinOutputFormatCombination e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  
  public static String CNToPinyin(String inputCN, String seg)
      throws BadHanyuPinyinOutputFormatCombination {
    char[] inputArray = inputCN.toCharArray();
    if (seg == null)
      seg = " ";
    HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
    format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    format.setVCharType(HanyuPinyinVCharType.WITH_V);
    String output = "";
    String[] temp = new String[10];
    for (int i = 0; i < inputArray.length; i++) {
      temp = PinyinHelper.toHanyuPinyinStringArray(inputArray[i], format);
      //若输入的汉字为多音字则会将不同的读音依次放入temp[]中,若不是多音字则只有temp[0]中有值
      for (int j = 0; j < temp.length; j++) {
 output += temp[j] + seg;
      }
    }
    return output;
  }
}

希望本文所述对大家Java程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/150794.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号