Using Google Translate/fr

From Lazarus wiki
Jump to navigationJump to search

English (en) français (fr) português (pt)

Vue d'ensemble

Il existe au moins deux manières d'accéder à Google Translate:

Pour plus d'informations sur l'API authentifiée avec OAuth2, veuillez consulter: Google Translate Getting Started

Voici un exemple d'utilisation de l'API gratuite :

Informations sur les paramètres de l' API

D'après une réponse sur Stack Overflow (What is the meaning of Google Translate query params?) voici une liste des paramètres de l'appel HTTP GET:

  • sl - code de la langue source (auto pour la détection automatique)
  • tl - langue de traduction
  • q - texte source / mot
  • ie - encodage d'entrée (une supposition)
  • oe - encodage de sortie (une supposition)
  • dt - peut être inclus plusieurs fois et spécifie ce qu'il faut retourner dans la réponse
  • dj - réponse JSON avec des noms au lieu de tableaux (dj=1)

Voici quelques valeurs pour dt:

  • t - traduction du texte source
  • at - traductions alternatives
  • rm - transcription / translittération des textes sources et traduits
  • bd - dictionnaire, au cas où le texte source est un mot (vous obtenez des traductions avec des articles, des traductions inversées, etc.)
  • md - définitions du texte source, si c'est un mot
  • ss - synonymes du texte source, s'il s'agit d'un mot
  • ex - exemples
  • rw - Voir aussi la liste


Se connecter à Google Translate

Cette fonction renverra la réponse JSON.

uses
  {...}, fpjson, fphttpclient, opensslsockets, {...}

function CallGoogleTranslate(AURL: String): TJSONStringType;
var
  client: TFPHTTPClient;
  doc: TStringList;
begin
  Result:= EmptyStr;
  doc:=TStringList.Create;
  client:=TFPHTTPClient.Create(nil);
  try
    client.Get(AURL,doc);
    Result:=doc.Text;
  finally
    doc.Free;
    client.Free;
  end;
end;

Analyser la réponse basée sur le tableau JSON

uses
  {...}, fpjson, jsonparser, HTTPDefs, {...}

const
  cArrayShortLanguages: Array [0..7] of String = (
    'auto',
    'en',
    'pt',
    'pl',
    'fr',
    'es',
    'it',
    'ru'
  );

procedure ParseArraysTranslate;
var
  URL: String;
  Index: integer;
  strResponse: TJSONStringType;
  jdResponse, jdTranslation, jdTranslationArray: TJSONData;
  jaTranslation, jaTranslationArray: TJSONArray;
begin

  URL:='https://translate.googleapis.com/translate_a/single?client=gtx'
    +'&q='+HTTPEncode({** METTRE LE TEXTE À TRADUIRE ICI **})
    +'&sl='+cArrayShortLanguages[0] // Détection automatique
    +'&tl='+cArrayShortLanguages[1] // Anglais
    +'&dt=t'
    +'&ie=UTF-8&oe=UTF-8'
    ;

  strResponse:= CallGoogleTranslate(URL);
  try
    jdResponse:= GetJSON(strResponse);

    jdTranslation:= jdResponse.FindPath('[0]');
    if (jdTranslation <> nil) and (jdTranslation.JSONType = jtArray) then
    begin
      jaTranslation:= TJSONArray(jdTranslation);
      for index:= 0 to Pred(jaTranslation.Count) do
      begin
        jdTranslationArray:= jaTranslation[Index];
        if (jdTranslationArray <> nil) and (jdTranslationArray.JSONType = jtArray) then
        begin
          jaTranslationArray:= TJSONArray(jdTranslationArray);
          WriteLN(Trim(jaTranslationArray[0].AsString));
        end;
      end;
    end;
  finally
    jdResponse.Free;
  end;
end;

Analyser la réponse basée sur l'objet JSON

uses
  {...}, fpjson, jsonparser, HTTPDefs, {...}

const
  cArrayShortLanguages: Array [0..7] of String = (
    'auto',
    'en',
    'pt',
    'pl',
    'fr',
    'es',
    'it',
    'ru'
  );
  cJSONSentences = 'sentences';
  cJSONTranslation = 'trans';
  cJSONSource = 'src';

procedure ParseObjectTranslate;
var
  URL: String;
  Index: integer;
  strResponse: TJSONStringType;
  jdResponse: TJSONData;
  joTranslation, joSentence: TJSONObject;
  jaSentencesArray: TJSONArray;
begin
  Application.ProcessMessages;
    URL:='https://translate.googleapis.com/translate_a/single?client=gtx'
      +'&q='+HTTPEncode({** METTRE LE TEXTE À TRADUIRE ICI **})
      +'&sl='+cArrayShortLanguages[0] // Détection automatique
      +'&tl='+cArrayShortLanguages[1] // Anglais
      +'&dt=t&dj=1' // dj=1 rend la réponse un objet JSON
      +'&ie=UTF-8&oe=UTF-8'
      ;

    strResponse:= CallGoogleTranslate(URL);
    try
      jdResponse:= GetJSON(strResponse);

      if (jdResponse <> nil) and (jdResponse.JSONType = jtObject) then
      begin
        joTranslation:= TJSONObject(jdResponse);
        jaSentencesArray:= TJSONArray(joTranslation.FindPath(cJSONSentences));
        for Index:=0 to Pred(jaSentencesArray.Count) do
        begin
          joSentence:= TJSONObject(jaSentencesArray[Index]);
          WriteLN(Trim(joSentence.Get(cJSONTranslation,'')));
        end;
      end;
    finally
      jdResponse.Free;
    end;
end;

Liens externes

Test Google Translate - Un référentiel GitHub qui illustre cet exemple.