2009-11-22 84 views
1

我正在使用Bing的API,更精确地说 - 翻译部分,除了一件事情 - 自动检测语言以外,它都工作得很好。这怎么可能?如何非法使用Bing Translate API?

我的代码工作正常,柜面有人需要看:

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 = en',我尝试着发送''作为源语言,但没有成功 - 没有结果。

如何使用自动检测?

回答

1

我用他们的Ajax API做了这个。如果使用空“from”参数构建查询,则该服务会自动检测该语言。

这是查询网址我格式化,使对服务的请求:

@"http://api.microsofttranslator.com/V2/Ajax.svc/Translate?appId={0}&from=&to={1}&text={2}" 

关键的事情是"from=&to={1}"

+0

必应翻译API的AppId现在已被弃用,并需要在标题中发送认证令牌...所以没有JavaScript的爱,你将需要使用服务器应用程序。 – 2012-05-08 15:07:55

+1

即使有''from =&to = {1}“'参数,它也不起作用(不再?)。 [docs](http://msdn.microsoft.com/en-us/library/ff512406.aspx)表示它仍然可以正常工作,但我没有看到它。它清楚地*检测到语言并正确地翻译它,但它不会告诉你它被检测为源语言。 – rkrzr 2014-01-30 10:46:16