Java實(shí)現(xiàn)將漢字轉(zhuǎn)化為漢語拼音的方法
更新時(shí)間:2015年12月21日 12:24:24 作者:李超@hicc
這篇文章主要介紹了Java實(shí)現(xiàn)將漢字轉(zhuǎn)化為漢語拼音的方法,實(shí)例演示了Java引用pinyin4j庫實(shí)現(xiàn)漢子轉(zhuǎn)化成拼音的使用技巧,需要的朋友可以參考下
本文實(shí)例講述了Java實(shí)現(xiàn)將漢字轉(zhuǎn)化為漢語拼音的方法。分享給大家供大家參考,具體如下:
網(wǎng)上亂轉(zhuǎn),偶然看到一個(gè)很有意思的小工具,名字叫pinyin4j,可以把漢字轉(zhuǎn)換為漢語拼音,利用他的話再配合上lucene、中文分詞就可以做出類似google那種輸入漢語拼音進(jìn)行全文檢索的功能了。實(shí)現(xiàn)的代碼如下
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 輸出漢語拼音時(shí)的分隔符
*
* HanyuPinyinOutputFormat提供了幾種輸出模式
* HanyuPinyinCaseType:設(shè)定輸入的結(jié)果是大寫英文還是小寫英文 LOWERCASE :小寫 UPPERCASE :大寫
* HanyuPinyinToneType:輸出是否表明音調(diào)和重音 WITH_TONE_NUMBER:標(biāo)明音調(diào) 如YE1 1-4表示 1-4聲
* WITHOUT_TONE:不顯示音調(diào)符 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;
}
}
希望本文所述對大家Java程序設(shè)計(jì)有所幫助。
相關(guān)文章
springboot2.3.1替換為其他的嵌入式servlet容器的詳細(xì)方法
這篇文章主要介紹了springboot2.3.1替換為其他的嵌入式servlet容器的方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
SpringBoot的@Value注解如何設(shè)置默認(rèn)值
這篇文章主要介紹了SpringBoot的@Value注解如何設(shè)置默認(rèn)值問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
Spring AOP手動實(shí)現(xiàn)簡單動態(tài)代理的代碼
今天小編就為大家分享一篇關(guān)于Spring AOP手動實(shí)現(xiàn)簡單動態(tài)代理的代碼,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-03-03

