C# 中文转换成拼音
利用微软的Microsoft.PinYinConverter能够查询出单个汉字的读音,
然后利用这个类通过排列组合就能得出词语中有多音情况下的集合。
代码
/// <summary>
/// 得到首字母
/// </summary>
/// <param name="text">中文文本</param>
/// <returns>中文文本的拼音首字母</returns>
public static string[] GetInitials(string text) => string.IsNullOrEmpty(text) ? null :
new List<ChineseChar>(text.Where(ch => Regex.IsMatch(ch.ToString(), @"[\u4e00-\u9fbb]")).Select(ch => new ChineseChar(ch))).
Select(cc => cc.Pinyins.Where(pinyin => !string.IsNullOrEmpty(pinyin)).Select(pinyin => pinyin[0]).Distinct())
.Aggregate((IEnumerable<IEnumerable<char>>)new IEnumerable<char>[] { Enumerable.Empty<char>() },
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] { item }),
(result) => result.Select(r => new string(r.ToArray()))).ToArray();
/// <summary>
/// 得到拼音
/// </summary>
/// <param name="text">中文文本</param>
/// <returns>中文文本的拼音</returns>
public static string[] GetPinYin(string text) => string.IsNullOrEmpty(text) ? null :
new List<ChineseChar>(text.Where(ch => Regex.IsMatch(ch.ToString(), @"[\u4e00-\u9fbb]")).Select(ch => new ChineseChar(ch))).
Select(cc => cc.Pinyins.Where(pinyin => !string.IsNullOrEmpty(pinyin)).Select(pinyin => pinyin.Substring(0, pinyin.Length - 1)).Distinct())
.Aggregate((IEnumerable<IEnumerable<string>>)new IEnumerable<string>[] { Enumerable.Empty<string>() },
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] { item }),
(result) => result.Select(r => string.Join(" ", r.Select(s => string.Concat(s[0], s.Substring(1).ToLower()))))).ToArray();