同系列文章:
源代码下载
接口定义:
Mandarin.thrift
/* 文件名称:Mandarin.thrift 作者:秦建辉 微信:splashcn 博客:http://www.firstsolver.com/wordpress/ 编译指令:thrift -r --gen csharp Mandarin.thrift 参考资料:http://thrift.apache.org */ namespace csharp Com.FirstSolver.Mandarin.Thrift enum GBCharset { GB2312 = 1, GBK = 2, GB18030 = 4 } service MandarinService { string QueryPinyin(1:string ucs4, 2:bool isDigitTone, 3:bool isUppercase), map<string,string> QueryHomophone(1:string ucs4, 2:GBCharset charset), map<string,string> GetHomophoneGroupedList(1:GBCharset charset) }
接口实现:
/* ---------------------------------------------------------- * 文件名称:MandarinServiceHandler.cs * * 作者:秦建辉 * * 微信:splashcn * * 博客:http://www.firstsolver.com/wordpress/ * * 开发环境: * Visual Studio 2017 * .NET Framework 4.5.2 * Apache Thrift v0.10.0 * * 版本历史: * V1.0 2017年07月16日 * 基于Thrift框架实现汉字拼音查询服务-接口实现 * * 参考资料: * http://thrift.apache.org ------------------------------------------------------------ */ using System; using System.Collections.Generic; using System.Text; namespace Com.FirstSolver.Mandarin.Thrift { public class MandarinServiceHandler : MandarinService.Iface { public Dictionary<string, string> GetHomophoneGroupedList(GBCharset charset) { try { // 获取检索字符集 HZCharSet SearchCharSet = (HZCharSet)Enum.Parse(typeof(HZCharSet), charset.ToString(), true); Dictionary<string, string> HomophoneList = new Dictionary<string, string>(); for (int i = 0; i < Pinyin.SYLLABLE_NUM; i++) { HomophoneList.Add(Pinyin.Syllable(i, true, true), Pinyin.Homophone(i, SearchCharSet)); } return HomophoneList; } catch { return null; } } public Dictionary<string, string> QueryHomophone(string ucs4, GBCharset charset) { try { // 获取检索字符集 HZCharSet SearchCharSet = (HZCharSet)Enum.Parse(typeof(HZCharSet), charset.ToString(), true); // 获取汉字拼音音节索引集合 ushort[] SyllableCollection = Pinyin.Pronunciation(char.ConvertToUtf32(ucs4, 0)); if (SyllableCollection == null) return null; Dictionary<string, string> HomophoneList = new Dictionary<string, string>(); foreach (ushort Index in SyllableCollection) { HomophoneList.Add(Pinyin.Syllable(Index, true, true), Pinyin.Homophone(Index, SearchCharSet)); } return HomophoneList; } catch { return null; } } public string QueryPinyin(string ucs4, bool isDigitTone, bool isUppercase) { try { // 获取汉字拼音音节索引集合 ushort[] SyllableCollection = Pinyin.Pronunciation(char.ConvertToUtf32(ucs4, 0)); if (SyllableCollection == null) return null; StringBuilder sb = new StringBuilder(); for (int i = 0; i < SyllableCollection.Length; i++) { if (i == 0) { sb.Append(Pinyin.Syllable(SyllableCollection[i], isDigitTone, isUppercase)); } else { sb.Append(" ").Append(Pinyin.Syllable(SyllableCollection[i], isDigitTone, isUppercase)); } } return sb.ToString(); } catch { return null; } } } }