感謝兩位博主,寫的比較全也很詳細(xì),都有提供源碼,大家可以參考下。
由于考慮到接口的需要,于是參考了 第一篇,文章中作者的源碼基本能滿足漢字轉(zhuǎn)拼音的需要,對于其他特殊的字符,也可以在進(jìn)行添加補(bǔ)充,不足之處就是不支持多音字,由于需要支持多音字的查詢,所以后面有查了下其他的文章,發(fā)現(xiàn)還沒有現(xiàn)成的文章(也可能本人的搜索水平比較水)。后來查找發(fā)現(xiàn)對于漢字轉(zhuǎn)拼音,原來微軟已經(jīng)提供了 Microsoft Visual Studio International Pack ,而且很強(qiáng)大。于是試了一下
查找 PinYinConverter
小試一下,使用也非常簡單,只要直接使用ChineseChar類進(jìn)行裝換就好
1 string ch = Console.ReadLine();2 ChineseChar cc = new ChineseChar(ch[0]);3 var pinyins = cc.Pinyins.ToList();4 pinyins.ForEach(Console.WriteLine);
結(jié)果如下:
我們可以看到, 行 的多音字有 hang,heng,xing 三個,這里連音標(biāo)也出來了,確實很方便。而我需要的功能是輸入 銀行 ,然后轉(zhuǎn)換為拼音是 yinhang,yinheng,yinxing, 首拼是 yh,yx。有ChineseChar 這個類的話做起來思路就簡單了。
1.首先對輸入的漢字進(jìn)行拆分
2.接著每個漢字用ChineseChar 獲取多個拼音
3.然后除去數(shù)字,去重,提取首字符,再在進(jìn)行組合就好了
于是寫了個幫助類進(jìn)行裝換,代碼如下:
public class PinYinConverterHelp { public static PingYinModel GetTotalPingYin(string str) { var chs = str.ToCharArray(); //記錄每個漢字的全拼 Dictionary<int, List<string>> totalPingYins = new Dictionary<int, List<string>>(); for (int i = 0; i < chs.Length; i++) { var pinyins = new List<string>(); var ch = chs[i]; //是否是有效的漢字 if (ChineseChar.IsValidChar(ch)) { ChineseChar cc = new ChineseChar(ch); pinyins = cc.Pinyins.Where(p => !string.IsNullOrWhiteSpace(p)).ToList(); } else { pinyins.Add(ch.ToString()); } //去除聲調(diào),轉(zhuǎn)小寫 pinyins = pinyins.ConvertAll(p => Regex.Replace(p, @"\d", "").ToLower()); //去重 pinyins = pinyins.Where(p => !string.IsNullOrWhiteSpace(p)).Distinct().ToList(); if (pinyins.Any()) { totalPingYins[i] = pinyins; } } PingYinModel result = new PingYinModel(); foreach (var pinyins in totalPingYins) { var items = pinyins.Value; if (result.TotalPingYin.Count <= 0) { result.TotalPingYin = items; result.FirstPingYin = items.ConvertAll(p => p.Substring(0, 1)).Distinct().ToList(); } else { //全拼循環(huán)匹配 var newTotalPingYins = new List<string>(); foreach (var totalPingYin in result.TotalPingYin) { newTotalPingYins.AddRange(items.Select(item => totalPingYin + item)); } newTotalPingYins = newTotalPingYins.Distinct().ToList(); result.TotalPingYin = newTotalPingYins; //首字母循環(huán)匹配 var newFirstPingYins = new List<string>(); foreach (var firstPingYin in result.FirstPingYin) { newFirstPingYins.AddRange(items.Select(item => firstPingYin + item.Substring(0, 1))); } newFirstPingYins = newFirstPingYins.Distinct().ToList(); result.FirstPingYin = newFirstPingYins; } } return result; } }
Console.WriteLine("請輸入中文:"); string str = Console.ReadLine(); var pingyins = PinYinConverterHelp.GetTotalPingYin(str); Console.WriteLine("全拼音:" + String.Join(",", pingyins.TotalPingYin)); Console.WriteLine("首音:" + String.Join(",", pingyins.FirstPingYin)); Console.WriteLine();
結(jié)果:
目前試過一些生僻字都是能支持,對于一些太偏的還沒試過,不過對于一般漢字轉(zhuǎn)拼音的,多音字支持這里就已經(jīng)足夠了。
這里僅僅是使用了 Microsoft Visual Studio International Pack 這個擴(kuò)展包里面的漢字轉(zhuǎn)拼音功能,其實里面還有中文、日文、韓文、英語等各國語言包,并提供方法實現(xiàn)互轉(zhuǎn)、獲、獲取字?jǐn)?shù)、甚至獲取筆畫數(shù)等等強(qiáng)大的功能,有興趣的朋友可以自行查詢下它的api。