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

网友投稿 183 2023-07-24


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[]) {

http:// trhttp://y {

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.sCCjYKuMBetVCharType(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程序设计有所帮助。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java中常见的日期操作(取值、转换、加减、比较)
下一篇:InputStreamReader 和FileReader的区别及InputStream和Reader的区别
相关文章

 发表评论

暂时没有评论,来抢沙发吧~