How to propertly use Bing Translate API?

别说谁变了你拦得住时间么 提交于 2019-12-08 07:53:29

问题


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;

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.

How do I use auto-detection?


回答1:


I did this using their Ajax API. If you build your query with a null "from" parameter, then the service auto-detects the language.

This is the query url I format to make requests to the service:

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

Key thing being "from=&to={1}".



来源:https://stackoverflow.com/questions/1778651/how-to-propertly-use-bing-translate-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!