陈元爱 發表於 2021-12-21 14:15:00

C#汉字转汉语拼音

<h1 id="一使用pinyinconvertercore获取汉语拼音">一、使用<code>PinYinConverterCore</code>获取汉语拼音</h1>
<p>最新在做一个搜索组件,需要使用汉语拼音的首字母查询出符合条件的物品名称,由于汉字存在多音字,所以自己写查询组件不太现实,因此,我们使用微软提供的<code>CHSPinYinConv</code>,<code>CHSPinYinConv</code>在.net core下载安装没有问题,但在.net framework会由于兼容性会安装失败,因此使用了<code>PinYinConverterCore</code>来实现汉字转拼音,<code>PinYinConverterCore</code>应该也是基于<code>CHSPinYinConv</code>开发的兼容包,后续的代码两个安装包环境下都可以使用。使用<code>Nuget</code>搜索<code>PinYinConverterCore</code>下载并安装,具体如下:</p>
<p><img src="https://s2.loli.net/2021/12/21/NvtFHOCT7Skeoi4.png" alt="image-20211221140230709" loading="lazy"></p>
<h1 id="二编写工具扩展类实现获取汉字的拼音">二、编写工具扩展类实现获取汉字的拼音</h1>
<p>由于汉字存在多音字,因此,通过汉字获取到的拼音是一个数组,具体如下:</p>
<pre><code class="language-c#">/// &lt;summary&gt;
    /// 汉字转换拼音
    /// &lt;/summary&gt;
    public static class PingYinUtil
    {
      private static Dictionary&lt;int, List&lt;string&gt;&gt; GetTotalPingYinDictionary(string text)
      {
            var chs = text.ToCharArray();

            //记录每个汉字的全拼
            Dictionary&lt;int, List&lt;string&gt;&gt; totalPingYinList = new Dictionary&lt;int, List&lt;string&gt;&gt;();

            for (int i = 0; i &lt; chs.Length; i++)
            {
                var pinyinList = new List&lt;string&gt;();

                //是否是有效的汉字
                if (ChineseChar.IsValidChar(chs))
                {
                  ChineseChar cc = new ChineseChar(chs);
                  pinyinList = cc.Pinyins.Where(p =&gt; !string.IsNullOrWhiteSpace(p)).ToList();
                }
                else
                {
                  pinyinList.Add(chs.ToString());
                }

                //去除声调,转小写
                pinyinList = pinyinList.ConvertAll(p =&gt; Regex.Replace(p, @"\d", "").ToLower());

                //去重
                pinyinList = pinyinList.Where(p =&gt; !string.IsNullOrWhiteSpace(p)).Distinct().ToList();
                if (pinyinList.Any())
                {
                  totalPingYinList = pinyinList;
                }
            }

            return totalPingYinList;
      }
      /// &lt;summary&gt;
      /// 获取汉语拼音全拼
      /// &lt;/summary&gt;
      /// &lt;param name="text"&gt;The string.&lt;/param&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      public static List&lt;string&gt; GetTotalPingYin(this string text)
      {
            var result = new List&lt;string&gt;();
            foreach (var pys in GetTotalPingYinDictionary(text))
            {
                var items = pys.Value;
                if (result.Count &lt;= 0)
                {
                  result = items;
                }
                else
                {
                  //全拼循环匹配
                  var newTotalPingYinList = new List&lt;string&gt;();
                  foreach (var totalPingYin in result)
                  {
                        newTotalPingYinList.AddRange(items.Select(item =&gt; totalPingYin + item));
                  }
                  newTotalPingYinList = newTotalPingYinList.Distinct().ToList();
                  result = newTotalPingYinList;
                }
            }
            return result;
      }

      /// &lt;summary&gt;
      /// 获取汉语拼音首字母
      /// &lt;/summary&gt;
      /// &lt;param name="text"&gt;&lt;/param&gt;
      /// &lt;returns&gt;&lt;/returns&gt;
      public static List&lt;string&gt; GetFirstPingYin(this string text)
      {
            var result = new List&lt;string&gt;();
            foreach (var pys in GetTotalPingYinDictionary(text))
            {
                var items = pys.Value;
                if (result.Count &lt;= 0)
                {
                  result = items.ConvertAll(p =&gt; p.Substring(0, 1)).Distinct().ToList();
                }
                else
                {
                  //首字母循环匹配
                  var newFirstPingYinList = new List&lt;string&gt;();
                  foreach (var firstPingYin in result)
                  {
                        newFirstPingYinList.AddRange(items.Select(item =&gt; firstPingYin + item.Substring(0, 1)));
                  }
                  newFirstPingYinList = newFirstPingYinList.Distinct().ToList();
                  result = newFirstPingYinList;
                }
            }
            return result;
      }
    }
</code></pre>
<h1 id="三编写测试用例">三、编写测试用例</h1>
<p>我们编写一个测试用例,通过输入的汉字获取到汉语拼音的全拼和首字母缩写,具体如下:</p>
<pre><code class="language-c#">               // 汉字输入
                string text = TextBoxInput.Text;

                // 获取到汉语拼音的全拼
                TextBoxTotal.Text = string.Join(",", text.GetTotalPingYin());

                // 获取到汉语拼音的首字母
                TextBoxFirst.Text = string.Join(",", text.GetFirstPingYin());
</code></pre>
<p><img src="https://s2.loli.net/2021/12/21/OeEbDQwVykr8qU7.png" alt="image-20211221140904565" loading="lazy"></p>
<p>我们编写录入一组用户名,然后根据输入输入的用户名的缩写,筛选出符合条件的人,我们可以使用<code>Linq</code>模糊查询,具体如下:</p>
<pre><code class="language-c#"> public class Student
    {
      public string Name { get; set; }
      public List&lt;string&gt; Pinyin { get; set; }
    }
</code></pre>
<pre><code class="language-c#">StudentList = new List&lt;Student&gt;
            {
                new Student() {Name = "张三"},
                new Student() {Name = "章黎"},
                new Student() {Name = "张三丰"},
                new Student() {Name = "李四"},
                new Student() {Name = "王五"},
                new Student() {Name = "John"},
                new Student() {Name = "W.吴"},
                new Student() {Name = "阿姨"},
                new Student() {Name = "阿胶"},
                new Student() {Name = "麦合苏提.麦合苏提"}
            };
</code></pre>
<pre><code class="language-c#"> var text = TextBoxSearch.Text;
            foreach (var student in StudentList)
            {
                student.Pinyin = student.Name.GetFirstPingYin();
            }

            StudentList = StudentList.Where(s =&gt; s.Pinyin.Exists(p=&gt;p.Contains(text))).ToList();
</code></pre>
<p><img src="https://s2.loli.net/2021/12/21/rH73bIuFoSOU8hM.png" alt="image-20211221141311784" loading="lazy"></p><br><br>
来源:https://www.cnblogs.com/dongweian/p/15715099.html
頁: [1]
查看完整版本: C#汉字转汉语拼音