中文转换成拼音

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();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值