CSharp: pinyin in net 5 汉字拼音声调
using System; using NPinyin; //https://github.com/WuTong1995/NPinyin using Microsoft.International.Converters.PinYinConverter; using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter; using System.Linq; using System.Text.RegularExpressions; using System.Text; /* css https://www.w3.org/International/questions/qa-ruby https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/rt https://www.microsoft.com/en-us/download/details.aspx?id=18970 */ namespace ConsoleApp1 { class Program { static void Main(string[] args) { var hans = "涂聚文是中国江西吉州人,言语成了抢功尽责的功臣,还要行为来值班吗"; var pinyin = new Pinyin(); pinyin.Option = new PinyinOption() { //Style = PinyinStyle.Normal, // 不带声调(默认) zhong wen Style = PinyinStyle.Tone, // 带声调 zhōng wén EnableInterval = true // 多个拼音之间是否启用间隔 zhong wen zhongwen }; var result = pinyin.ConvertToPinyin(hans); // zhong wen var pi = GetPinYin(hans); var pin = GetPinYinFull(hans); Console.WriteLine("Hello C# World! geovindu\t\n"); Console.WriteLine(result.ToString()+ "\t\n"); Console.WriteLine(pi.ToString() + "\t\n"); Console.WriteLine(pin.ToString() + "\t\n"); } /// <summary> /// 获得中文字符串的拼音 没有声调 /// </summary> /// <param name="str"></param> /// <returns></returns> private static string GetPinYin(string str) { string py = ""; for (int i = 0; i < str.Length; i++) { if (ChineseChar.IsValidChar(str[i]))//判断当前字符是不是汉字 { ChineseChar cc = new ChineseChar(str[i]);//构造方法 py +=" "+ cc.Pinyins[0].TrimEnd('1', '2', '3', '4', '5').ToLower(); } else//不是汉字的话 加本身 { py += " " + str[i]; } } return py; } ///<summary> /// 汉字 /// </summary> private static string ChineseReg = "^[\\u4E00-\\u9FA5]+$"; public static string GetPinYinFull(string str) { var pySb = new StringBuilder(); foreach (var itemChar in str) { //过滤非汉字的字符,直接返回 var reg = new Regex(ChineseReg); if (!reg.IsMatch(itemChar.ToString())) { pySb.Append(" " + itemChar); } else { var chineseChar = new ChineseChar(itemChar); //var pyStr = chineseChar.Pinyins.First().ToLower(); var pyStr = chineseChar.Pinyins.First().ToUpper(); pySb.Append(" " + pyStr.Substring(0, pyStr.Length - 1)); } } return pySb.ToString(); } // <summary> /// 简体转换为繁体 /// </summary> /// <param name="str">简体字</param> /// <returns>繁体字</returns> public static string GetTraditional(string str) { string r = string.Empty; r = ChineseConverter.Convert(str, ChineseConversionDirection.SimplifiedToTraditional); return r; } /// <summary> /// 繁体转换为简体 /// </summary> /// <param name="str">繁体字</param> /// <returns>简体字</returns> public static string GetSimplified(string str) { string r = string.Empty; r = ChineseConverter.Convert(str, ChineseConversionDirection.TraditionalToSimplified); return r; } } }
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)