前言
虽然百度翻译相对于谷歌翻译在准确性方面还有很大的提升空间,但网络的现实情况及百度翻译接口的免费易用性方面让我们选择百度翻译接口。下面来一起看看详细的步骤吧
方法如下
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内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!