C#汉字转拼音首字母全拼支持多音字
|
admin
2021年1月29日 9:18
本文热度 2892
|
1.首先在NuGet安装pingyinConverter
2.下载-安装-引用ChineseChar.dll到项目中
官网了解:http://www.microsoft.com/zh-cn/download/confirmation.aspx?id=15251
3.直接上代码了
1 public class PinYinConverterHelp
2 {
3 public static PingYinModel GetTotalPingYin(string str)
4 {
5 var chs = str.ToCharArray();
6 //记录每个汉字的全拼
7 Dictionary<int, List<string>> totalPingYins = new Dictionary<int, List<string>>();
8 for (int i = 0; i < chs.Length; i++)
9 {
10 var pinyins = new List<string>();
11 var ch = chs[i];
12 //是否是有效的汉字
13 if (ChineseChar.IsValidChar(ch))
14 {
15 ChineseChar cc = new ChineseChar(ch);
16 pinyins = cc.Pinyins.Where(p => !string.IsNullOrWhiteSpace(p)).ToList();
17 }
18 else
19 {
20 pinyins.Add(ch.ToString());
21 }
22
23 //去除声调,转小写
24 pinyins = pinyins.ConvertAll(p => Regex.Replace(p, @"\d", "").ToLower());
25 //去重
26 pinyins = pinyins.Where(p => !string.IsNullOrWhiteSpace(p)).Distinct().ToList();
27 if (pinyins.Any())
28 {
29 totalPingYins[i] = pinyins;
30 }
31 }
32 PingYinModel result = new PingYinModel() {
33 TotalPingYin=new List<string>(),
34 FirstPingYin=new List<string>()
35 };
36 foreach (var pinyins in totalPingYins)
37 {
38 var items = pinyins.Value;
39 if (result.TotalPingYin.Count <= 0)
40 {
41 result.TotalPingYin = items;
42 result.FirstPingYin = items.ConvertAll(p => p.Substring(0, 1)).Distinct().ToList();
43 }
44 else
45 {
46 ////全拼循环匹配(根据个人需求来选择此代码)
47 //var newTotalPingYins = new List<string>();
48 //foreach (var totalPingYin in result.TotalPingYin)
49 //{
50 // newTotalPingYins.AddRange(items.Select(item => totalPingYin + item));
51 //}
52 //newTotalPingYins = newTotalPingYins.Distinct().ToList();
53 //result.TotalPingYin = newTotalPingYins;
54
55 //首字母循环匹配
56 var newFirstPingYins = new List<string>();
57 foreach (var firstPingYin in result.FirstPingYin)
58 {
59 newFirstPingYins.AddRange(items.Select(item => firstPingYin + item.Substring(0, 1)));
60 }
61 newFirstPingYins = newFirstPingYins.Distinct().ToList();
62 result.FirstPingYin = newFirstPingYins;
63 }
64 }
65 return result;
66 }
67
68 /// <summary>
69 /// 获取首字母并转换成大写
70 /// </summary>
71 /// <param name="str"></param>
72 /// <returns></returns>
73 public static string GetPingYinFirstUpper(string str)
74 {
75 var output = GetTotalPingYin(str);
76 return string.Join("", output.FirstPingYin.ToArray()).ToUpper();
77 }
78 public class PingYinModel
79 {
80 public List<string> TotalPingYin { get; internal set; }
81 public List<string> FirstPingYin { get; internal set; }
82 }
83 }
4.不用感谢,请叫我红领巾
该文章在 2021/1/29 9:18:09 编辑过