如何正确使用必应翻译 API? [英] How to propertly use Bing Translate API?
问题描述
我正在使用 Bing 的 API,更准确地说 - 翻译部分,除了一件事 - 自动检测语言之外,一切都很好.这怎么可能?
I'm using the API of Bing, more precisely - the translation part, and it all works quite well except one thing - auto detection of language. How is that possible?
我的代码运行良好,以防有人需要查看:
My code is working fine,incase someone needs to look at:
function HTTPEncode(const AStr: string): string;
const
NoConversion = ['A'..'Z', 'a'..'z', '*', '@', '.', '_', '-'];
var
i: integer;
begin
Result := '';
for i := 1 to Length(AStr) do
begin
if CharInSet(AStr[i],NoConversion) then
Result := Result + AStr[i]
else
Result := Result + Format('%%%.2x',[ord(AStr[i])]);
end;
end;
function GetTranslation(text, fromLang, toLang: string): string;
var
xmldoc: TXMLDocument;
inode,mnode,rnode,irnode: IXMLNode;
j: integer;
uri: string;
idhttp:TIdHttp;
begin
Result := '';
idhttp:=TIdHttp.Create(nil);
xmldoc := TXMLDocument.Create(application);
try
xmldoc.LoadFromXML(idhttp.Get('http://api.search.live.net/xml.aspx?Appid=' + AppID + '&query='+HTTPEncode(text)+
'&sources=translation'+
'&Translation.SourceLanguage=' + fromLang +
'&Translation.TargetLanguage=' + toLang));
finally
idhttp.Free;
end;
try
inode := xmldoc.ChildNodes.FindNode('SearchResponse');
if Assigned(inode) then
begin
uri := 'http://schemas.microsoft.com/LiveSearch/2008/04/XML/translation';
mnode := inode.ChildNodes.FindNode('Translation',uri);
if Assigned(mnode) then
begin
rnode := mnode.ChildNodes.FindNode('Results',uri);
if Assigned(rnode) then
begin
irnode := rnode.ChildNodes.FindNode('TranslationResult',uri);
if Assigned(irnode) then
Result := irnode.ChildNodes.FindNode('TranslatedTerm',uri).NodeValue;
end;
end;
end;
finally
xmldoc.Free;
end;
end;
begin
ShowMessage(GetTranslation('Hello!','en','de'));
end;
我在使用自动检测时跟踪了来自 http://www.microsofttranslator.com/ 的数据包功能,结果是 'from=;'而如果源语言是英语,它会是 'from=en;'.我也尝试发送 '' 作为源语言,但没有成功 - 没有结果.
I followed the packets from http://www.microsofttranslator.com/ when using auto-detection feature, the result was 'from=;' whereas if source language is English it'd be 'from=en;'.I tried aswell sending '' as source language,but it didn't work out - no result.
如何使用自动检测?
推荐答案
以下是 API 版本 3 的示例:
Here is an example for API version 3:
- 没有
from
参数 - 英文文本
detectedLanguage
结果为en
- 我认为
score
对这个结果有 100% 的把握
- no
from
parameter - English text
detectedLanguage
results inen
- I read
score
as 100% sure about this result
$ curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&textType=html&to=fr" \
-d "[{'Text':'Underbeds'}]"> -H "Ocp-Apim-Subscription-Key:YOUR_KEY_HERE" \
> -H "Ocp-Apim-Subscription-Region:global" \
> -H "Content-Type: application/json" \
> -d "[{'Text':'Underbeds'}]"
[{"detectedLanguage":{"language":"en","score":1.0},"translations":[{"text":"Sous-lits","to":"fr"}]}]
这篇关于如何正确使用必应翻译 API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!