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

时间:2021-12-08 10:29:44

原文链接: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”,下面程序片段可以获得汉字的拼音:

 using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.International.Converters.PinYinConverter; namespace MSPinyin
{
class Program
{
static void Main(string[] args)
{
char[] hanzi = { '囧', '妍' }; foreach (char c in hanzi)
{
ChineseChar chineseChar = new ChineseChar(c); //因为一个汉字可能有多个读音,pinyins是一个集合
var pinyins = chineseChar.Pinyins;
String firstPinyin = null;
//下面的方法只是简单的获得了集合中第一个非空元素
foreach (var pinyin in pinyins)
{
if (pinyin != null)
{
//拼音的最后一个字符是音调
firstPinyin = pinyin.Substring(, pinyin.Length - );
break;
}
} Console.WriteLine(firstPinyin);
}
Console.Read();
}
}
}