将汉字转化为汉语拼音的小工具

网上乱转,偶然看到一个很有意思的小工具,名字叫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();
        }
    }
    /**
     * @parm inputCN 输入的中文字符串
     * @parm seg 输出汉语拼音时的分隔符
     * 
     * HanyuPinyinOutputFormat提供了几种输出模式
     * HanyuPinyinCaseType:设定输入的结果是大写英文还是小写英文 LOWERCASE :小写 UPPERCASE :大写
     * HanyuPinyinToneType:输出是否表明音调和重音 WITH_TONE_NUMBER:标明音调 如YE1 1-4表示 1-4声
     * WITHOUT_TONE:不显示音调符 HanyuPinyinVCharType :输出要用何种的拼音编码
     */
    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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值