C#:一个 RESTful 风格的汉字拼音查询系统

源代码下载

Mandarin 20170712.zip

RESTful 接口定义
IMandarinService.cs

/* ----------------------------------------------------------
 * 文件名称:IMandarinService.cs
 * 
 * 作者:秦建辉
 *
 * 微信:splashcn
 *
 * 博客:http://www.firstsolver.com/wordpress/
 *
 * 开发环境:
 *      Visual Studio V2017
 *      .NET Framework 4.5.2
 * 
 * 版本历史:
 *      V1.0	2017年07月11日
 *              定义拼音查询的Restful Service接口
 * ---------------------------------------------------------- */
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Collections.Generic;

namespace Com.FirstSolver.Mandarin
{
    [ServiceContract]
    public interface IMandarinService
    {
        /// <summary>
        /// 查询汉字拼音
        /// </summary>
        /// <param name="ucs4">要查询的汉字字符</param>
        /// <param name="isDigitTone">是否数字标调</param>
        /// <param name="isUppercase">是否字母大写</param>
        /// <returns>拼音音节串,多个音节以空格间隔</returns>
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "pinyin/{ucs4}?x={isDigitTone}&y={isUppercase}")]
        string QueryPinyin(string ucs4, bool isDigitTone = true, bool isUppercase = true);

        /// <summary>
        /// 获取查询汉字的同音字集合
        /// </summary>
        /// <param name="ucs4">要查询的汉字字符</param>
        /// <param name="charset">字符集范围,其值有:GB2312、GBK、GB18030</param>
        /// <returns></returns>
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "homophone/{ucs4}?charset={charset}")]
        KeyValuePair<string, string>[] QueryHomophone(string ucs4, string charset);

        /// <summary>
        /// 获取同音字分组列表
        /// </summary>
        /// <param name="charset">字符集范围,其值有:GB2312、GBK、GB18030</param>
        /// <returns>同音字分组列表</returns>
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "homophone/{charset}")]
        KeyValuePair<string, string>[] GetHomophoneGroupedList(string charset);
    }
}

RESTful 接口实现
MandarinService.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace Com.FirstSolver.Mandarin
{
    public class MandarinService : IMandarinService
    {
        /// <summary>
        /// 查询汉字拼音
        /// </summary>
        /// <param name="ucs4">要查询的汉字</param>
        /// <param name="isDigitTone">是否采用数字标调</param>
        /// <param name="isUppercase">是否音节字母大写</param>
        /// <returns>拼音音节串,多个音节以空格间隔</returns>        
        public string QueryPinyin(string ucs4, bool isDigitTone = true, bool isUppercase = true)
        {
            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;
            }
        }

        /// <summary>
        /// 查询同音字
        /// </summary>
        /// <param name="ucs4">要查询的汉字</param>
        /// <param name="charset">要检索的字符集,可能的值有GB2312、GBK、GB18030</param>
        /// <returns>同音字集合</returns>
        public KeyValuePair<string, string>[] QueryHomophone(string ucs4, string charset)
        {
            try
            {
                // 获取检索字符集
                if (string.IsNullOrEmpty(charset) || !charset.StartsWith("GB", true, System.Globalization.CultureInfo.InvariantCulture)) return null;
                HZCharSet SearchCharSet = (HZCharSet)Enum.Parse(typeof(HZCharSet), charset, true);

                // 获取汉字拼音音节索引集合
                ushort[] SyllableCollection = Pinyin.Pronunciation(char.ConvertToUtf32(ucs4, 0));
                if (SyllableCollection == null) return null;

                List<KeyValuePair<string, string>> HomophoneList = new List<KeyValuePair<string, string>>();
                foreach (ushort Index in SyllableCollection)
                {
                    HomophoneList.Add(new KeyValuePair<string, string>(Pinyin.Syllable(Index, true, true), Pinyin.Homophone(Index, SearchCharSet)));
                }
                return HomophoneList.ToArray();
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 获取同音字分组列表
        /// </summary>
        /// <param name="charset">要检索的字符集,可能的值有GB2312、GBK、GB18030</param>
        /// <returns>同音字分组列表</returns>
        public KeyValuePair<string, string>[] GetHomophoneGroupedList(string charset)
        {
            try
            {
                // 获取检索字符集
                if (string.IsNullOrEmpty(charset) || !charset.StartsWith("GB", true, System.Globalization.CultureInfo.InvariantCulture)) return null;
                HZCharSet SearchCharSet = (HZCharSet)Enum.Parse(typeof(HZCharSet), charset, true);

                List<KeyValuePair<string, string>> HomophoneList = new List<KeyValuePair<string, string>>();
                for (int i = 0; i < Pinyin.SYLLABLE_NUM; i++)
                {
                    HomophoneList.Add(new KeyValuePair<string, string>(Pinyin.Syllable(i, true, true), Pinyin.Homophone(i, SearchCharSet)));
                }
                return HomophoneList.ToArray();
            }
            catch
            {
                return null;
            }
        }
    }
}

服务启动
Program.cs

/* ----------------------------------------------------------
 * 文件名称:Program.cs
 * 
 * 作者:秦建辉
 * 微信:splashcn
 * 
 * 版本历史:
 *      V1.0	2017年07月12日
 *              测试拼音查询的Restful Service
 *              
 * 使用说明:
 *      1.先以管理员身份执行如下命令以解决 System.ServiceModel.AddressAccessDeniedException 问题
 *             netsh http add urlacl url= http://+:8000/MandarinService/ user="\Everyone"
 *             
 *      2.然后运行本程序
 *      
 *      3.在浏览器地址栏中输入如下命令进行测试
 *          拼音测试
 *              http://localhost:8000/MandarinService/pinyin/长?x=true&y=true
 *              http://localhost:8000/MandarinService/pinyin/长?x=false&y=true
 *              
 *          同音字测试
 *              http://localhost:8000/MandarinService/homophone/长?charset=GB2312
 *              http://localhost:8000/MandarinService/homophone/长?charset=GBK
 *              http://localhost:8000/MandarinService/homophone/长?charset=GB18030
 *              
 *          同音字分组列表测试
 *             http://localhost:8000/MandarinService/homophone/GB2312
 *             http://localhost:8000/MandarinService/homophone/GBK
 *             http://localhost:8000/MandarinService/homophone/GB18030
 * ---------------------------------------------------------- */
using Com.FirstSolver.Mandarin;
using System;
using System.ServiceModel.Web;

namespace MandarinServiceConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            using (WebServiceHost host = new WebServiceHost(typeof(MandarinService), new Uri("http://localhost:8000/MandarinService")))
            {
                host.Opened += delegate
                {
                    Console.WriteLine("Hosted successfully.");
                };
                host.Open();
                Console.ReadLine();
            }
        }
    }
}

测试服务
Program.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;

namespace Splash
{
    public class HomophoneGroupedList
    {
        public KeyValuePair<string, string>[] GetHomophoneGroupedListResult;
    }

    class Program
    {
        static void Main(string[] args)
        {
            TestHomophoneGroupedList();
        }

        static void TestHomophoneGroupedList()
        {
            const string OUTFILE = "GB2312音节分类表.txt";
            try
            {
                string RequestUriString = "http://localhost:8000/MandarinService/homophone/GB2312";
                HttpWebRequest request = WebRequest.Create(RequestUriString) as HttpWebRequest;
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(HomophoneGroupedList));
                    HomophoneGroupedList x = (HomophoneGroupedList)deseralizer.ReadObject(response.GetResponseStream());
                    using (StreamWriter sw = new StreamWriter(OUTFILE, false, Encoding.UTF8))
                    {
                        foreach (KeyValuePair<string, string> Item in x.GetHomophoneGroupedListResult)
                        {
                            if (!String.IsNullOrEmpty(Item.Value))
                            {
                                sw.WriteLine(Item.Key);
                                sw.WriteLine(Item.Value);
                            }
                        }
                    }
                }

                Console.WriteLine("成功!");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

Comments are closed.