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 = "http://api.fanyi.baidu.com/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目录下,可以用以下代码读取后翻译,用以解决每次翻译,百度翻译有句子长短限制的问题。TBTxtName.txt为要翻译的文件名,要替换的符号以及语言可自己选择。
public void ReadAndTranslate() { string TextName = “TBTxtName.txt”; 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]; 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内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)