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

C#漢字轉拼音

mov 技術 except class 常用 val pat init src

下載並引入兩個dll文件 NPinyin.dll 和 ChnCharInfo.dll

  其實這兩個dll 任何一個都可以實現漢字轉拼音,然而 NPinyin.dll 收錄的漢字並不全,但是很人性化,能識別一些常用的漢字。ChnCharInfo.dll 是微軟的很全但是不人性化。另外本套代碼外有一個自己維護的個別漢字文件,例如一些多音字姓氏。

  本程序的使用場景是姓名轉拼音,所以先判斷第一個漢字是否在自己維護的拼音庫中存在,如果存在者優先使用這個庫中漢字所對應的拼音,如果不存在者優先使用NPinyin庫中轉化拼音的方法,轉化失敗再使用微軟提供的ChnCharInfo中轉拼音的方法。

  Main函數

技術分享圖片
 static void Main(string[] args)
        {
            string path = @"PinYinDic.txt";
            StreamReader sr = new StreamReader(path, Encoding.Default);
            Dictionary<char, string> pinyinDic = JsonConvert.DeserializeObject<Dictionary<char, string>>(sr.ReadToEnd());

            string name = "薄露露";
            Console.WriteLine(name+PinYinHelper.ConvertToAllSpell(name, pinyinDic).ToLower());
            Console.ReadKey();
        }
技術分享圖片
PinYinHelper類
技術分享圖片
public class PinYinHelper
    {
        private static Encoding gb2312 = Encoding.GetEncoding("GB2312");

        /// <summary>
        /// 漢字轉全拼
        /// </summary>
        /// <param name="strChinese"></param>
        /// <returns></returns>
        public static string ConvertToAllSpell(string strChinese, IDictionary<char, string> pinyinDic = null)
        {
            try
            {
                if (strChinese.Length != 0)
                {
                    StringBuilder fullSpell = new StringBuilder();
                    for (int i = 0; i < strChinese.Length; i++)
                    {
                        var chr = strChinese[i];
                        string pinyin = string.Empty;
                        if (i == 0)
                        {
                            pinyin = GetFromPinYinDic(chr, pinyinDic); 
                        }
                        if (pinyin.Length == 0)
                        {
                            pinyin = GetSpell(chr);
                        }
                        fullSpell.Append(pinyin);
                    }

                    return fullSpell.ToString().ToLower();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("全拼轉化出錯!" + e.Message);
            }

            return string.Empty;
        }

        /// <summary>
        /// 漢字轉首字母
        /// </summary>
        /// <param name="strChinese"></param>
        /// <returns></returns>
        public static string GetFirstSpell(string strChinese)
        {
            //NPinyin.Pinyin.GetInitials(strChinese)  有Bug  洺無法識別
            //return NPinyin.Pinyin.GetInitials(strChinese);

            try
            {
                if (strChinese.Length != 0)
                {
                    StringBuilder fullSpell = new StringBuilder();
                    for (int i = 0; i < strChinese.Length; i++)
                    {
                        var chr = strChinese[i];
                        fullSpell.Append(GetSpell(chr)[0]);
                    }

                    return fullSpell.ToString().ToUpper();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("首字母轉化出錯!" + e.Message);
            }

            return string.Empty;
        }

        private static string GetSpell(char chr)
        {
            var coverchr = NPinyin.Pinyin.GetPinyin(chr);
            bool isChineses = ChineseChar.IsValidChar(coverchr[0]);
            if (isChineses)
            {
                ChineseChar chineseChar = new ChineseChar(coverchr[0]);
                foreach (string value in chineseChar.Pinyins)
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        return value.Remove(value.Length - 1, 1);
                    }
                }
            }

            return coverchr;

        }

        /// <summary>
        /// 從字典獲取拼音
        /// </summary>
        /// <param name="c">字</param>
        /// <param name="pinyinDic">字典</param>
        /// <returns></returns>
        private static string GetFromPinYinDic(char c, IDictionary<char, string> pinyinDic)
        {
            if (pinyinDic == null
                || pinyinDic.Count == 0
                || !pinyinDic.ContainsKey(c))
            {
                return "";
            }

            return pinyinDic[c];
        }
    }
技術分享圖片

接下來是本程序維護的 PinYinDic.txt,該文件放在"\bin\Debug"目錄下,當然也可以不使用。

技術分享圖片
{
"紅":"hong",
"賈":"jia",
"薄":"bo",
"褚":"chu",
"翟":"zhai",
"郇":"xun",
"蓋":"ge",
"樂":"yue",
"區":"ou",
"蔔":"bu",
"曾":"zeng",
"丁":"ding",
"無":"wu",
"長":"chang",
"其":"qi",
"巷":"xiang",
"將":"jiang",
"氏":"shi",
"色":"se",
"系":"xi",
"重":"chong",
"乜":"nie",
"孛":"bo",
"卒":"zu",
"單":"shan",
"解":"xie",
"仇":"qiu",
"隗":"wei",
"查":"zha",
"繁":"po",
"樸":"piao"
}
技術分享圖片

C#漢字轉拼音