• Asp.NET调用有道翻译API


    调用有道API进行翻译,如图:

    HTML:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="FanYi.aspx.cs" Inherits="FanYi" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>翻译</title>
        <style type="text/css">
            #sourceWord
            {
                height: 30px;
                font-size: 16pt;
                font-weight: bold;
                border: 1px green solid;
                line-height: 30px;
            }
            #Translate
            {
                font-size: 14pt;
                margin-left: 10px;
            }
            #panel_Dict
            {
                margin-top: 15px;
            }
            .query
            {
                font-size: 16pt;
                color: Green;
                font-weight: bold;
            }
            .phonetic
            {
                color: Gray;
                font-size: 13pt;
            }
            .wordGroup
            {
                font-size: 13pt;
                color: #35a1d4;
                font-weight: bold;
                margin-right: 0.5em;
                margin-top: 10px;
                margin-bottom: 0px;
                display: block;
            }
            legend
            {
                font-size: 12pt;
                color: Gray;
            }
            fieldset
            {
                display: inline;
                padding: 10px;
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="sourceWord" runat="server" Style=" 500px;" TextMode="SingleLine"
                MaxLength="200"></asp:TextBox>
            <asp:Button ID="Translate" runat="server" Text="Translate" OnClick="Translate_Click" />
            <asp:Panel ID="panel_Dict" runat="server">
                <asp:Label ID="lblQuery" runat="server" Text="" CssClass="query"></asp:Label>
                <asp:Label ID="lblPhonetic" runat="server" Text="" CssClass="phonetic"></asp:Label>
                <br />
                <fieldset runat="server" id="fieldset1">
                    <legend>近义词</legend>
                    <asp:Label ID="lblExplains" runat="server" Text="" CssClass="wordGroup"></asp:Label>
                </fieldset>
                <br />
                <fieldset runat="server" id="fieldset2">
                    <legend>翻译</legend>
                    <asp:Label ID="lblTranslation" runat="server" Text=""></asp:Label>
                </fieldset>
                <br />
                <fieldset runat="server" id="fieldset3">
                    <legend>短语</legend>
                    <asp:Label ID="lblWeb" runat="server" Text=""></asp:Label>
                </fieldset>
                <br />
            </asp:Panel>
        </div>
        </form>
    </body>
    </html>


    C#:

    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Json;
    using System.Web;
    
    public partial class FanYi : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            translation();
        }
        /// <summary>
        /// 翻译并显示结果
        /// </summary>
        private void translation()
        {
            lblTranslation.Text = "";
            lblWeb.Text = "";
            lblQuery.Text = sourceWord.Text;
            lblPhonetic.Text = "";
            lblExplains.Text = "";
            if (sourceWord.Text.Trim() == "")
            {
                return;
            }
            translationData data = YouDaoTranslateTool(sourceWord.Text.Trim());
            if (data.errorCode == 0)
            {
                if (data.basic != null)
                {
                    fieldset1.Visible = true;
                    if (data.basic.phonetic != "")
                    {
                        lblPhonetic.Text = "[" + data.basic.phonetic + "]";
                    }
                    for (int i = 0; i < data.basic.explains.Count; i++)
                    {
                        lblExplains.Text += data.basic.explains[i] + "<br/>";
                    }
                }
                else
                {
                    fieldset1.Visible = false;
                }
                for (int i = 0; i < data.translation.Count; i++)
                {
                    lblTranslation.Text += data.translation[i] + "<br/>";
                }
                if (data.web != null)
                {
                    fieldset3.Visible = true;
                    for (int i = 0; i < data.web.Count; i++)
                    {
                        lblWeb.Text += "<span class='wordGroup'>" + data.web[i].key + "</span>";
                        for (int j = 0; j < data.web[i].value.Count; j++)
                        {
                            lblWeb.Text += data.web[i].value[j] + (j == data.web[i].value.Count - 1 ? "" : "; ");
                        }
                        lblWeb.Text += "<br/>";
                    }
                }
                else
                {
                    fieldset3.Visible = false;
                }
            }    
        }
    
        protected void Translate_Click(object sender, EventArgs e)
        {
        }
    
        /// <summary>
        /// 请求Web数据,返回实体类
        /// </summary>
        /// <param name="sourceWord">要翻译的内容</param>
        /// <returns></returns>
        public translationData YouDaoTranslateTool(string sourceWord)
        {
            /* 
            调用:http://fanyi.youdao.com/openapi.do?keyfrom=?&key=?&type=data&doctype=json&version=1.1&q=中国人
            */
            string serverUrl = @"http://fanyi.youdao.com/openapi.do?keyfrom=morninglight&key=1612199890&type=data&doctype=json&version=1.1&q="
            + HttpUtility.UrlEncode(sourceWord);
            WebRequest request = WebRequest.Create(serverUrl);
            WebResponse response = request.GetResponse();
    
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(translationData));
            return (translationData)serializer.ReadObject(response.GetResponseStream());
        }
        #region 翻译结果数据实体类
            /*
            json数据格式举例
            {
                "errorCode":0
                "query":"翻译",
                "translation":["translation"], // 有道翻译
                "basic":{ // 有道词典-基本词典
                    "phonetic":"fān yì",
                    "explains":[
                        "translate",
                        "interpret"
                    ]
                },
                "web":[ // 有道词典-网络释义
                    {
                        "key":"翻译",
                        "value":["translator","translation","translate","Interpreter"]
                    },
                    {...}
                ]
            }
            */
        [DataContract]
        public class translationData
        {
            [DataMember]
            public int errorCode { get; set; }
            [DataMember]
            public string query { get; set; }
            [DataMember]
            public List<string> translation { get; set; }
            [DataMember]
            public translationBasic basic { get; set; }
            [DataMember]
            public List<translationWeb> web { get; set; }
        }
        [DataContract]
        public class translationBasic
        {
            [DataMember]
            public string phonetic { get; set; }
            [DataMember]
            public List<string> explains { get; set; }
        }
        [DataContract]
        public class translationWeb
        {
            [DataMember]
            public List<string> value { get; set; }
            [DataMember]
            public string key { get; set; }
        }
        #endregion
    }


     

  • 相关阅读:
    常见逻辑谬误
    4 WPF依赖属性
    11 WPF样式和行为
    17 WPF控件模板
    3 WPF布局
    4.6.3 The LRParsing Algorithm
    4.6 Introduction to LR Parsing: Simple LR
    19 WPF 数据绑定
    分布式系统部署、监控与进程管理的几重境界
    运维知识体系
  • 原文地址:https://www.cnblogs.com/apollokk/p/6713911.html
Copyright © 2020-2023  润新知