下载并引入两个dll文件 NPinyin.dll 和 ChnCharInfo.dll
其实这两个dll 任何一个都可以实现汉字转拼音,然而 NPinyin.dll 收录的汉字并不全,但是很人性化,能识别一些常用的汉字。ChnCharInfo.dll 是微软的很全但是不人性化。另外本套代码外有一个自己维护的个别汉字文件,例如一些多音字姓氏。
本程序的使用场景是姓名转拼音,所以先判断第一个汉字是否在自己维护的拼音库中存在,如果存在者优先使用这个库中汉字所对应的拼音,如果不存在者优先使用NPinyin库中转化拼音的方法,转化失败再使用微软提供的ChnCharInfo中转拼音的方法。
Main函数
static void Main(string[] args)
{
string path = @"PinYinDic.txt";
StreamReader sr = new StreamReader(path, Encoding.Default);
Dictionary<char, string> pinyinDic = JsonConvert.DeserializeObject<Dictionary<char, string>>(sr.ReadToEnd());
string name = "薄露露";
Console.WriteLine(name+PinYinHelper.ConvertToAllSpell(name, pinyinDic).ToLower());
Console.ReadKey();
}
PinYinHelper类
public class PinYinHelper
{
private static Encoding gb2312 = Encoding.GetEncoding("GB2312");
/// <summary>
/// 汉字转全拼
/// </summary>
/// <param name="strChinese"></param>
/// <returns></returns>
public static string ConvertToAllSpell(string strChinese, IDictionary<char, string> pinyinDic = null)
{
try
{
if (strChinese.Length != 0)
{
StringBuilder fullSpell = new StringBuilder();
for (int i = 0; i < strChinese.Length; i++)
{
var chr = strChinese[i];
string pinyin = string.Empty;
if (i == 0)
{
pinyin = GetFromPinYinDic(chr, pinyinDic);
}
if (pinyin.Length == 0)
{
pinyin = GetSpell(chr);
}
fullSpell.Append(pinyin);
}
return fullSpell.ToString().ToLower();
}
}
catch (Exception e)
{
Console.WriteLine("全拼转化出错!" + e.Message);
}
return string.Empty;
}
/// <summary>
/// 汉字转首字母
/// </summary>
/// <param name="strChinese"></param>
/// <returns></returns>
public static string GetFirstSpell(string strChinese)
{
//NPinyin.Pinyin.GetInitials(strChinese) 有Bug 洺无法识别
//return NPinyin.Pinyin.GetInitials(strChinese);
try
{
if (strChinese.Length != 0)
{
StringBuilder fullSpell = new StringBuilder();
for (int i = 0; i < strChinese.Length; i++)
{
var chr = strChinese[i];
fullSpell.Append(GetSpell(chr)[0]);
}
return fullSpell.ToString().ToUpper();
}
}
catch (Exception e)
{
Console.WriteLine("首字母转化出错!" + e.Message);
}
return string.Empty;
}
private static string GetSpell(char chr)
{
var coverchr = NPinyin.Pinyin.GetPinyin(chr);
bool isChineses = ChineseChar.IsValidChar(coverchr[0]);
if (isChineses)
{
ChineseChar chineseChar = new ChineseChar(coverchr[0]);
foreach (string value in chineseChar.Pinyins)
{
if (!string.IsNullOrEmpty(value))
{
return value.Remove(value.Length - 1, 1);
}
}
}
return coverchr;
}
/// <summary>
/// 从字典获取拼音
/// </summary>
/// <param name="c">字</param>
/// <param name="pinyinDic">字典</param>
/// <returns></returns>
private static string GetFromPinYinDic(char c, IDictionary<char, string> pinyinDic)
{
if (pinyinDic == null
|| pinyinDic.Count == 0
|| !pinyinDic.ContainsKey(c))
{
return "";
}
return pinyinDic[c];
}