温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#基于百度AI如何实现机器翻译功能

发布时间:2022-01-12 14:10:36 来源:亿速云 阅读:187 作者:柒染 栏目:开发技术

C#基于百度AI如何实现机器翻译功能,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

    随着“一带一路”政策的开展,各种项目迎接而来,语言不通就成为了痛点。

    作为开发人员,相信大家对于翻译不陌生吧,百度翻译,有道词典、谷歌翻译等等或多或少都用过(汉-英,汉-日,汉-俄等等)。

    我们现在就基于百度Ai开放平台进行机器翻译,demo使用的是C#控制台应用程序,后续有需要的可以嫁接到指定项目中使用。

    1、注册百度账号api,创建自己的Api应用

    注册地址: https://login.bce.baidu.com/

    注册登录之后,在“产品服务” 菜单下找到机器翻译 ,点击进入,如下图:

    C#基于百度AI如何实现机器翻译功能

    注意,这里我们需要先进行 领取免费资源 ,开发完成后根据后期需求决定是否进行付费操作,如下图所示:

    C#基于百度AI如何实现机器翻译功能

    C#基于百度AI如何实现机器翻译功能

    领取后,创建我们的Api应用,如下图(主要是Api Key和Secret Key):

    C#基于百度AI如何实现机器翻译功能

    C#基于百度AI如何实现机器翻译功能

    C#基于百度AI如何实现机器翻译功能

    2、创建vs控制台应用程序

    创建VS控制台应用程序,命名为TranslateProject。

    .NET Framework/.NET Core的都可以,甚至于Web应用也行,因为这是Api操作。

    C#基于百度AI如何实现机器翻译功能

    3、编写程序并调试

    post请求工具类

    创建一个http请求接口帮助类(WebRequest方式API请求方式(Post/Get)),命名为 HttpTool(自定义命名),大家可以在网上找一个,或者用下面的:

    /// <summary>
            /// post请求方式
            /// </summary>
            /// <param name="url">请求路径</param>
            /// <param name="parms">传入的值,格式为:{city:"上海",city2:"重庆"}</param>
            /// <param name="token"></param>
            /// <param name="ContentType"></param>
            /// <returns></returns>
            public string HttpPost(string url, string parms, string token,string ContentType= "application/json")
            {
                string result = string.Empty;
                try
                {
                    if (url.StartsWith("https:"))
                    {
                        //要调用https的API接口,一定要加这句
                        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                    }
    
                    Encoding encoding = Encoding.UTF8;  //转译编码
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//创建
                    request.Method = "POST";   //post请求的一些标准参数配置
                    request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
                    request.ContentType = ContentType;
    
                    //自定义头部内容
                    if (!string.IsNullOrEmpty(token))
                    {
                        request.Headers.Add(HttpRequestHeader.Authorization, token);  //添加token
                    }
    
                    byte[] buffer = encoding.GetBytes(parms);  //译编传入的值格式化为可识别
                    request.ContentLength = buffer.Length;  //post传值参数标配
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //尝试获得要请求的URL的返回消息
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        result = reader.ReadToEnd();
                    }
                }
                catch (Exception ex)
                {
                    result = "";
                }
                return result;
            }

    文本翻译-通用版

    通用版API文档:https://cloud.baidu.com/doc/MT/s/4kqryjku9 

    直接看文档就可以了,我这里把代码展示一下,大家拷贝一下就可以执行。

    如下代码和展示:

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace TranslateProject
    {
        class Program
        {
            // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务(百度云应用的AK)
            private static String clientId = "qNldYXXtIr2pKBQsv242369Y";
            // 百度云中开通对应服务应用的 Secret Key(百度云应用的SK)
            private static String clientSecret = "L6gemOD3pM2PmafyQUBnXpCGEemk18mR";
            static void Main(string[] args)
            {
                try
                {
                    #region 文本翻译-通用版
    
                    //获取Token:详细见 https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
                    string TokenJson = getAccessToken();
                    if (!string.IsNullOrEmpty(TokenJson))
                    {
                        AccessToken TokenEntity = JsonConvert.DeserializeObject<AccessToken>(TokenJson);
                        if (!string.IsNullOrEmpty(TokenEntity.error))
                        {
                            if (TokenEntity.error == "invalid_client" && TokenEntity.error_description == "unknown client id")
                                Console.WriteLine("API Key不正确");
                            else if (TokenEntity.error == "invalid_client" && TokenEntity.error_description == "Client authentication failed")
                                Console.WriteLine("Secret Key不正确");
                            else
                                Console.WriteLine("未知错误:获取Token失败");
                            Console.ReadKey();
                            return;
                        }
    
                        string URL = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token="+ TokenEntity.access_token;
                        string q = "文本翻译是百度翻译依托领先的自然语言处理技术推出的在线文本翻译服务,可支持中、英、日、韩等200+语言互译,100+语种自动检测。";
                        string parms = "{ \"q\":\"" + q + "\",\"from\":\"zh\",\"to\":\"en\"}"; //from:翻译源语言     to:翻译目标语言     q:请求翻译内容
    
                        HttpTool httppost = new HttpTool();
                        var strJson = httppost.HttpPost(URL, parms, "", "application/json;charset=utf-8");
                        Console.WriteLine(strJson);
                        Console.ReadKey();
                    }
    
                    #endregion
                }
                catch (Exception ex)
                {
                    Console.WriteLine("翻译失败:" + ex.Message);
                }
            }
    
            //调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
            public static String getAccessToken()
            {
                try
                {
                    String authHost = "https://aip.baidubce.com/oauth/2.0/token";
                    HttpClient client = new HttpClient();
                    List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
                    paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                    paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
                    paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
    
                    HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
                    String result = response.Content.ReadAsStringAsync().Result;
                    return result;
                }
                catch (Exception ex)
                {
                    return "";
                }
                
            }
                    
            public class AccessToken
            {
                public string refresh_token { get; set; }
                public int expires_in { get; set; }
                public string scope { get; set; }
                public string session_key { get; set; }
                public string access_token { get; set; }
                public string session_secret { get; set; }
                public string error { get; set; }
                public string error_description { get; set; }
    
            }
        }
    }

    C#基于百度AI如何实现机器翻译功能

    关于C#基于百度AI如何实现机器翻译功能问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    ai
    AI