文字转拼音与简写
Posted ——君——
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文字转拼音与简写相关的知识,希望对你有一定的参考价值。
引用的插件为微软的 Microsoft.International.Converters.PinYinConverter
在NuGet中查找 PinYinConverter
1 public class PingYinModel 2 { 3 public List<string> TotalPingYin = new List<string>(); 4 public List<string> FirstPingYin = new List<string>(); 5 } 6 7 public ActionResult About() 8 { 9 //ViewBag.Message = "Your application description page."; 10 PingYinModel pingyins = GetTotalPingYin("银行,(孢)"); 11 12 ViewBag.pinyins = "银行,(孢) <br/>"; 13 ViewBag.pinyins += "全拼音:" + String.Join(",", pingyins.TotalPingYin) + "<br/>"; 14 ViewBag.pinyins += "首音:" + String.Join(",", pingyins.FirstPingYin); 15 return View(); 16 } 17 public static PingYinModel GetTotalPingYin(string str) 18 { 19 var chs = str.ToCharArray(); 20 //记录每个汉字的全拼 21 Dictionary<int, List<string>> totalPingYins = new Dictionary<int, List<string>>(); 22 for (int i = 0; i < chs.Length; i++) 23 { 24 var pinyins = new List<string>(); 25 var ch = chs[i]; 26 //是否是有效的汉字 27 if (ChineseChar.IsValidChar(ch)) 28 { 29 ChineseChar cc = new ChineseChar(ch); 30 pinyins = cc.Pinyins.Where(p => !string.IsNullOrWhiteSpace(p)).ToList(); 31 } 32 else 33 { 34 pinyins.Add(ch.ToString()); 35 } 36 37 //去除声调,转小写 38 pinyins = pinyins.ConvertAll(p => Regex.Replace(p, @"\\d", "").ToLower()); 39 //去重 40 pinyins = pinyins.Where(p => !string.IsNullOrWhiteSpace(p)).Distinct().ToList(); 41 if (pinyins.Any()) 42 { 43 totalPingYins[i] = pinyins; 44 } 45 } 46 PingYinModel result = new PingYinModel(); 47 foreach (var pinyins in totalPingYins) 48 { 49 var items = pinyins.Value; 50 if (result.TotalPingYin.Count <= 0) 51 { 52 result.TotalPingYin = items; 53 result.FirstPingYin = items.ConvertAll(p => p.Substring(0, 1)).Distinct().ToList(); 54 } 55 else 56 { 57 //全拼循环匹配 58 var newTotalPingYins = new List<string>(); 59 foreach (var totalPingYin in result.TotalPingYin) 60 { 61 newTotalPingYins.AddRange(items.Select(item => totalPingYin + item)); 62 } 63 newTotalPingYins = newTotalPingYins.Distinct().ToList(); 64 result.TotalPingYin = newTotalPingYins; 65 66 //首字母循环匹配 67 var newFirstPingYins = new List<string>(); 68 foreach (var firstPingYin in result.FirstPingYin) 69 { 70 newFirstPingYins.AddRange(items.Select(item => firstPingYin + item.Substring(0, 1))); 71 } 72 newFirstPingYins = newFirstPingYins.Distinct().ToList(); 73 result.FirstPingYin = newFirstPingYins; 74 } 75 } 76 return result; 77 }
效果图
以上是关于文字转拼音与简写的主要内容,如果未能解决你的问题,请参考以下文章