Sign in Join
Wiki copytemporary

Using Google Translate/pt: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Using Google Translate/pt

OldNewLine
1+## Introdução
2+
3+Existem pelo menos duas maneiras de acessar o Google Translate:
4+
5+- Uma forma gratuita, mas controlada.
6+- Usando a API autenticada com OAuth2.
7+
8+Este é um exemplo de uso do primeiro.
9+
10+Para obter informações sobre o último, é favor consultar: [Google Translate Getting Started](https://developers.google.com/translate/v2/getting_started)
11+
12+## Informações sobre os parâmetros
13+
14+De acordo com uma resposta no Stack Overflow ([What is the meaning of Google Translate query params?](https://stackoverflow.com/a/29537590/8167)) aqui está uma lista dos parâmetros para a chamada HTTP GET:
15+
16+- sl - código do idioma de origem (auto para detecção automática)
17+- tl - linguagem de tradução
18+- q - texto / palavra fonte
19+- ie - codificação de entrada (um palpite)
20+- oe - codificação de saída (um palpite)
21+- dt - pode ser incluído mais de uma vez e especifica o que retornar na resposta
22+- dj - resposta JSON com nomes em vez de apenas matrizes (dj=1)
23+
24+Aqui estão alguns valores para dt:
25+
26+- t - tradução do texto fonte
27+- at - traduções alternativas
28+- rm - transcrição / transliteração de textos fonte e traduzidos
29+- bd - dicionário, caso o texto de origem seja uma palavra (você obtém traduções com artigos, traduções reversas, etc.)
30+- md - definições de texto de origem, se for uma palavra
31+- ss - sinônimos de texto fonte, se for uma palavra
32+- ex - exemplos
33+- rw - Veja também a lista
34+
35+## Contactando o Google
36+
37+Esta função retornará a resposta em JSON.
38+
39+``` pascal
40+uses
41+ {...}, fpjson, fphttpclient, opensslsockets, {...}
42+
43+function CallGoogleTranslate(AURL: String): TJSONStringType;
44+var
45+ client: TFPHTTPClient;
46+ doc: TStringList;
47+begin
48+ Result:= EmptyStr;
49+ doc:=TStringList.Create;
50+ client:=TFPHTTPClient.Create(nil);
51+ try
52+ client.Get(AURL,doc);
53+ Result:=doc.Text;
54+ finally
55+ doc.Free;
56+ client.Free;
57+ end;
58+end;
59+```
60+
61+## Analisando a resposta baseada em matriz JSON
62+
63+``` pascal
64+uses
65+ {...}, fpjson, jsonparser, HTTPDefs, {...}
66+
67+const
68+ cArrayShortLanguages: Array [0..7] of String = (
69+ 'auto',
70+ 'en',
71+ 'pt',
72+ 'pl',
73+ 'fr',
74+ 'es',
75+ 'it',
76+ 'ru'
77+ );
78+
79+procedure ParseArraysTranslate;
80+var
81+ URL: String;
82+ Index: integer;
83+ strResponse: TJSONStringType;
84+ jdResponse, jdTranslation, jdTranslationArray: TJSONData;
85+ jaTranslation, jaTranslationArray: TJSONArray;
86+begin
87+
88+ URL:='https://translate.googleapis.com/translate_a/single?client=gtx'
89+ +'&q='+HTTPEncode({** COLOQUE O TEXTO PARA TRADUZIR AQUI **})
90+ +'&sl='+cArrayShortLanguages[0] // Deteção automática
91+ +'&tl='+cArrayShortLanguages[1] // Inglês
92+ +'&dt=t'
93+ +'&ie=UTF-8&oe=UTF-8'
94+ ;
95+
96+ strResponse:= CallGoogleTranslate(URL);
97+ try
98+ jdResponse:= GetJSON(strResponse);
99+
100+ jdTranslation:= jdResponse.FindPath('[0]');
101+ if (jdTranslation <> nil) and (jdTranslation.JSONType = jtArray) then
102+ begin
103+ jaTranslation:= TJSONArray(jdTranslation);
104+ for index:= 0 to Pred(jaTranslation.Count) do
105+ begin
106+ jdTranslationArray:= jaTranslation[Index];
107+ if (jdTranslationArray <> nil) and (jdTranslationArray.JSONType = jtArray) then
108+ begin
109+ jaTranslationArray:= TJSONArray(jdTranslationArray);
110+ WriteLN(Trim(jaTranslationArray[0].AsString));
111+ end;
112+ end;
113+ end;
114+ finally
115+ jdResponse.Free;
116+ end;
117+end;
118+```
119+
120+## Analisando a resposta baseada em objeto JSON
121+
122+``` pascal
123+uses
124+ {...}, fpjson, jsonparser, HTTPDefs, {...}
125+
126+const
127+ cArrayShortLanguages: Array [0..7] of String = (
128+ 'auto',
129+ 'en',
130+ 'pt',
131+ 'pl',
132+ 'fr',
133+ 'es',
134+ 'it',
135+ 'ru'
136+ );
137+ cJSONSentences = 'sentences';
138+ cJSONTranslation = 'trans';
139+ cJSONSource = 'src';
140+
141+procedure ParseObjectTranslate;
142+var
143+ URL: String;
144+ Index: integer;
145+ strResponse: TJSONStringType;
146+ jdResponse: TJSONData;
147+ joTranslation, joSentence: TJSONObject;
148+ jaSentencesArray: TJSONArray;
149+begin
150+ Application.ProcessMessages;
151+ URL:='https://translate.googleapis.com/translate_a/single?client=gtx'
152+ +'&q='+HTTPEncode({** COLOQUE O TEXTO PARA TRADUZIR AQUI **})
153+ +'&sl='+cArrayShortLanguages[0] // Deteção automática
154+ +'&tl='+cArrayShortLanguages[1] // Inglês
155+ +'&dt=t&dj=1' // dj=1 faz com que a resposta seja um objeto JSON
156+ +'&ie=UTF-8&oe=UTF-8'
157+ ;
158+
159+ strResponse:= CallGoogleTranslate(URL);
160+ try
161+ jdResponse:= GetJSON(strResponse);
162+
163+ if (jdResponse <> nil) and (jdResponse.JSONType = jtObject) then
164+ begin
165+ joTranslation:= TJSONObject(jdResponse);
166+ jaSentencesArray:= TJSONArray(joTranslation.FindPath(cJSONSentences));
167+ for Index:=0 to Pred(jaSentencesArray.Count) do
168+ begin
169+ joSentence:= TJSONObject(jaSentencesArray[Index]);
170+ WriteLN(Trim(joSentence.Get(cJSONTranslation,'')));
171+ end;
172+ end;
173+ finally
174+ jdResponse.Free;
175+ end;
176+end;
177+```
178+
179+## Links externos
180+
181+[Test Google Translate](https://github.com/gcarreno/TestGoogleTranslate) - Um repositório [GitHub](https://github.com) que demonstra este exemplo.
182+
183+---
184+*From the Free Pascal wiki, page "Using Google Translate/pt", as it stood on 2021-12-16 after a change by Gcarreno, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history