forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPingYinHelper.cs
More file actions
108 lines (100 loc) · 3.67 KB
/
PingYinHelper.cs
File metadata and controls
108 lines (100 loc) · 3.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using Microsoft.International.Converters.PinYinConverter;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Blog.Core.Common.Helper
{
/// <summary>
/// 汉字转换拼音
/// </summary>
public static class PingYinUtil
{
private static Dictionary<int, List<string>> GetTotalPingYinDictionary(string text)
{
var chs = text.ToCharArray();
//记录每个汉字的全拼
Dictionary<int, List<string>> totalPingYinList = new Dictionary<int, List<string>>();
for (int i = 0; i < chs.Length; i++)
{
var pinyinList = new List<string>();
//是否是有效的汉字
if (ChineseChar.IsValidChar(chs[i]))
{
ChineseChar cc = new ChineseChar(chs[i]);
pinyinList = cc.Pinyins.Where(p => !string.IsNullOrWhiteSpace(p)).ToList();
}
else
{
pinyinList.Add(chs[i].ToString());
}
//去除声调,转小写
pinyinList = pinyinList.ConvertAll(p => Regex.Replace(p, @"\d", "").ToLower());
//去重
pinyinList = pinyinList.Where(p => !string.IsNullOrWhiteSpace(p)).Distinct().ToList();
if (pinyinList.Any())
{
totalPingYinList[i] = pinyinList;
}
}
return totalPingYinList;
}
/// <summary>
/// 获取汉语拼音全拼
/// </summary>
/// <param name="text">The string.</param>
/// <returns></returns>
public static List<string> GetTotalPingYin(this string text)
{
var result = new List<string>();
foreach (var pys in GetTotalPingYinDictionary(text))
{
var items = pys.Value;
if (result.Count <= 0)
{
result = items;
}
else
{
//全拼循环匹配
var newTotalPingYinList = new List<string>();
foreach (var totalPingYin in result)
{
newTotalPingYinList.AddRange(items.Select(item => totalPingYin + item));
}
newTotalPingYinList = newTotalPingYinList.Distinct().ToList();
result = newTotalPingYinList;
}
}
return result;
}
/// <summary>
/// 获取汉语拼音首字母
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static List<string> GetFirstPingYin(this string text)
{
var result = new List<string>();
foreach (var pys in GetTotalPingYinDictionary(text))
{
var items = pys.Value;
if (result.Count <= 0)
{
result = items.ConvertAll(p => p.Substring(0, 1)).Distinct().ToList();
}
else
{
//首字母循环匹配
var newFirstPingYinList = new List<string>();
foreach (var firstPingYin in result)
{
newFirstPingYinList.AddRange(items.Select(item => firstPingYin + item.Substring(0, 1)));
}
newFirstPingYinList = newFirstPingYinList.Distinct().ToList();
result = newFirstPingYinList;
}
}
return result;
}
}
}