資源簡介
用matlab+百度翻譯API+md5加密函數(shù)寫成的翻譯函數(shù),需要自己添加API id和密匙哦。

代碼片段和文件信息
%百度翻譯函數(shù)
%注冊API網(wǎng)站:http://api.fanyi.baidu.com/api/trans/product/index;關(guān)于語言的代號請見:http://api.fanyi.baidu.com/api/trans/product/apidoc中的通用翻譯API技術(shù)文檔;
%調(diào)用時:輸入:BaiduTranFunction(被翻譯詞的語言,翻譯出的詞的語言,被翻譯的詞,百度API的id,百度API的密匙);
%如:希望將‘蘋果’從中文翻譯成英文;你的id是:999999;密匙是:11111,則輸入:BaiduTranFunction(‘zh‘‘en‘‘蘋果‘‘999999‘‘11111‘);
function?TranslateResult=BaiduTranFunction(OrilanguageNewlanguagewanttotranslateappidmishi)
%創(chuàng)建一個名為salt的隨機(jī)數(shù)
salt=floor(rand*100);
%不變的前面的大地址
Bigweb=‘http://api.fanyi.baidu.com/api/trans/vip/translate?‘;
%要翻譯的詞,如果對翻譯的詞進(jìn)行url的編碼,防止matlab自身無法編碼,導(dǎo)致無法運(yùn)行
Q=sprintf(‘q=%s&‘urlencode(wanttotranslate));
%翻譯的詞的語言
From=sprintf(‘from=%s&‘Orilanguage);
%希望翻譯成的語言
To=sprintf(‘to=%s&‘Newlanguage);
%百度翻譯API的賬號
Appid=sprintf(‘a(chǎn)ppid=%s&‘a(chǎn)ppid);
%之前的隨機(jī)數(shù)
Salt=sprintf(‘salt=%d&‘salt);
%通過md5的加密方式得到sign的內(nèi)容:具體參見百度翻譯API的規(guī)則:http://api.fanyi.baidu.com/api/trans/product/apidoc中的通用API接入方式
%此處調(diào)用了md5函數(shù);
Sign=sprintf(‘sign=%s‘lower(md5(unicode2native(sprintf(‘%s%s%d%s‘a(chǎn)ppidwanttotranslatesaltmishi)‘UTF-8‘))));
%將前面的多個變量拼成最終的API地址,為了防止需要翻譯的句子中有空格而導(dǎo)致出現(xiàn)警告,因此將地址中的空格替換成%20;
ALL=strrep(sprintf(‘%s%s%s%s%s%s%s‘BigwebQFromToAppidSaltSign)‘?‘‘%20‘);
%讀取API的地址
Urlread=urlread(ALL);
%將讀取的內(nèi)容拆分成“***“的幾個部分,而所需要的翻譯結(jié)果,永遠(yuǎn)是第9個;
unic=regexp(Urlread‘“.*?“‘‘match‘);
%把“去掉
beta=strrep(unic{9}‘“‘‘‘);
TranslateResult=sprintf(strrep(beta‘\u‘‘\x‘));
end
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件????????1704??2019-04-21?21:03??BaiduTranFunction.m
?????文件????????4357??2019-04-21?10:44??md5.m
- 上一篇:矩量法matlab程序設(shè)計(jì).doc
- 下一篇:人工魚群算法
評論
共有 條評論