[转]使用微软的官方类库CHSPinYinConv获得汉字拼音

原文链接:http://outofmemory.cn/code-snippet/4392/ms-CHSPinYinConv-convert-hanzi-to-pinyin

微软为中文,日文以及韩文提供了额外的支持,我们可以从微软的网站上下载相关文字处理的类库,下载地址如下:

http://download.microsoft.com/download/5/7/3/57345088-ACF8-4E9B-A9A7-EBA35452DEF2/vsintlpack1.zip

下载的是一个zip包,里面有多个安装文件,我们只安装“CHSPinYinConv.msi”就可以了,安装之后在安装目录下会有“ChnCharInfo.dll”文件,这个文件可以做汉字相关的处理,不止有文字,还有笔画读音等汉字相关的信息。

需要在项目中引入“ChnCharInfo.dll”,下面程序片段可以获得汉字的拼音:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using Microsoft.International.Converters.PinYinConverter;
 5 
 6 namespace MSPinyin
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             char[] hanzi = { '', '' };
13 
14             foreach (char c in hanzi)
15             {
16                 ChineseChar chineseChar = new ChineseChar(c);
17 
18                 //因为一个汉字可能有多个读音,pinyins是一个集合
19                 var pinyins = chineseChar.Pinyins;
20                 String firstPinyin = null;
21                 //下面的方法只是简单的获得了集合中第一个非空元素
22                 foreach (var pinyin in pinyins)
23                 {
24                     if (pinyin != null)
25                     {
26                         //拼音的最后一个字符是音调
27                         firstPinyin = pinyin.Substring(0, pinyin.Length - 1);
28                         break;
29                     }
30                 }
31 
32                 Console.WriteLine(firstPinyin);
33             }
34             Console.Read();
35         }
36     }
37 }

 

 
posted @ 2014-02-12 17:02  chutianshu_1981  阅读(2526)  评论(0编辑  收藏  举报