1. 程式人生 > >漢字轉拼音

漢字轉拼音

col [] 沒有 行為 pin bin -1 風險 static

使用的庫: pinyin4j

鏈接:http://pan.baidu.com/s/1gf23Nkn 密碼:b4sf

使用pinyin4j獲取漢字的簡拼/全拼示例:

 1 package prinyin4j;
 2 
 3 import java.util.Scanner;
 4 import net.sourceforge.pinyin4j.PinyinHelper;
 5 import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
 6 import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
7 import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; 8 import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; 9 import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;; 10 11 public class Main { 12 13 static Scanner input = new Scanner(System.in);
14 15 public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination { 16 17 HanyuPinyinOutputFormat hypyfm = new HanyuPinyinOutputFormat(); 18 hypyfm.setCaseType(HanyuPinyinCaseType.LOWERCASE); 19 hypyfm.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
20 hypyfm.setVCharType(HanyuPinyinVCharType.WITH_V); 21 22 System.out.println("請輸入聯系人的名字:"); 23 String str = input.next(); 24 char[] ch = str.toCharArray(); 25 StringBuilder fullPrint = new StringBuilder(); 26 StringBuilder simplePrint = new StringBuilder(); 27 for (int i = 0; i < ch.length; ++i) { 28 String[] temp = PinyinHelper.toHanyuPinyinStringArray(ch[i],hypyfm); 29 simplePrint.append(temp[0].charAt(0) ); 30 fullPrint.append(temp[0]); 31 } 32 System.out.println(simplePrint); 33 System.out.println(fullPrint.toString()); 34 } 35 36 }

運行截圖:

技術分享

不過還有個問題:

技術分享

廈門的簡拼和全拼錯了,廈(xia)被發音成廈(sha)!!!

事實上,只要是有兩種以上發音的字,就存在這種風險.

ps: 更佳的漢字轉拼音java開源類庫 https://github.com/stuxuhai/jpinyin

技術分享

當然,JPinyin並沒有修復多音字的缺陷,233...

pinyin4j對單個漢字進行處理,多音字會返回多個讀音,必然產生這種風險

然而要根據語境進行準確發音,這太難了,即使對人類來說,這都不是件簡單的事,

但總有辦法,能讓機器產生類似人類的選擇行為 , 機器學習 or 深度學習 or AI !!!

TODO: 暑假來波機器學習入門!!

漢字轉拼音