C#调⽤百度翻译API实现⼀个翻译功能
前⾔
虽然百度翻译相对于⾕歌翻译在准确性⽅⾯还有很⼤的提升空间,但⽹络的现实情况及百度翻译接⼝的免费易⽤性⽅⾯让我们选择百度翻译接⼝。下⾯来⼀起看看详细的步骤吧
⽅法如下
appId 和 passWord 需要到申请
using System;
using System.Net;
using System.Web.Security;
using System.Web.Script.Serialization;
namespace TranslatorOfWang
{
class TranslateFunction
{
public static string Translate(string content)
{
string languageFrom = "en", languageTo = "zh";
if (Translate(content, languageFrom, languageTo).Error_code == null)
{
return Translate(content, languageFrom, languageTo).Trans_result[0].Dst;
}
else
return Translate(content, languageFrom, languageTo).Error_msg;
}
public static PostResult Translate(string content, string languageFrom, string languageTo)
{
string appId = "2018111519456789", passWord = "gMk8wEKxENvbpUcvFxxx", randomNum = new Random().Next().ToString();
string md5Sign = FormsAuthentication.HashPasswordForStoringInConfigFile(appId + content + randomNum + passWord, "MD5").ToLower();
string FullRequest = "api.fanyi.baidu/api/trans/vip/translate?q=" + content + "&from=" + languageFrom + "&to=" + languageTo + "&appid=" + appId + "&salt=" + randomNum + "&sign=" + md5Sign;            string m_Content = new WebClient().DownloadString(FullRequest);
PostResult m_postResult = new JavaScriptSerializer().Deserialize<PostResult>(m_Content);
return m_postResult;
}
public  class PostResult{
public string Error_code { set; get; }
public string Error_msg { set; get; }
public string From { set; get; }
public string To { set; get; }
public TranslateContent[] Trans_result { set; get; }
}
public class TranslateContent
{
public string Src { set; get; }
public string Dst { set; get; }
}
}
}
PostResult为百度API返回的值类型组成的⼀个⾃定义类,类⾥的每个名字和百度翻译API返回值⾥名字要⼀致。
升级功能:
先将要翻译的⽂本写⼊TXT⽂档,存⼊主⽬录下的File⽬录下,可以⽤以下代码读取后翻译,⽤以解决每次翻译,百度翻译有句⼦长短限制的问题。为要翻译的⽂件名,要替换的符号以及语⾔可⾃⼰选择。
public void ReadAndTranslate()
{
string TextName = “”;
string path = "File/";
StreamReader sr = new StreamReader(path + TextName + ".txt", Encoding.Default);
StreamWriter m_SW = new StreamWriter(path + DateTime.Now.ToString("yyyymmddhhmm") + "TransLated" + ".txt", true);
//去除符号重新定义句⼦
string xx = sr.ReadToEnd();
string[] split = xx.Split(new char[] { '.','!','?', ';', ',', ':' });
string content;
for (int i = 0; i < split.Length; i++)
{
content = split[i];
writeline方法的作用
if (content != null & content != "" & content != " " & content != "\n" & content != "\t" & content != "\r")
{
string line = TranslationFunction.Translate(content);
m_SW.WriteLine(line);
//m_SW.WriteLine(content);
}
}
m_SW.Dispose();
m_SW.Close();
}
总结
到此这篇关于C#调⽤百度翻译API实现⼀个翻译功能的⽂章就介绍到这了,更多相关C#调⽤百度翻译API内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。