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內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!