用JSON 和 Google 实现全文翻译
代码
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Memo2: TMemo;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses MsXML, SuperObject;
//字符串到 UTF8 编码的函数, 用于 Google 地址
function ToUTF8Encode(str: string): string;
var
b: Byte;
begin
for b in BytesOf(UTF8Encode(str)) do
Result := Format('%s%s%.2x', [Result, '%', b]);
end;
//翻译函数
function Translate(str, RequestLanguage, ResultLanguage: string): string;
const
BaseUrl = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=';
var
Url: string;
jo: ISuperObject;
req: IXMLHTTPRequest;
begin
Url := BaseUrl + ToUTF8Encode(str) + '&langpair=' + RequestLanguage + '%7C' + ResultLanguage;
req := CoXMLHTTP.Create;
req.open('Get', Url, False, EmptyParam, EmptyParam);
req.send(EmptyParam);
jo := SO(req.responseText);
Result := jo.Format('%responseData.translatedText%');
end;
//英译汉
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo2.Text := Translate(Memo1.Text, 'en', 'zh-cn');
end;
//汉译英
procedure TForm1.Button2Click(Sender: TObject);
begin
Memo1.Text := Translate(Memo2.Text, 'zh-cn', 'en');
end;
end.
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Memo2: TMemo;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses MsXML, SuperObject;
//字符串到 UTF8 编码的函数, 用于 Google 地址
function ToUTF8Encode(str: string): string;
var
b: Byte;
begin
for b in BytesOf(UTF8Encode(str)) do
Result := Format('%s%s%.2x', [Result, '%', b]);
end;
//翻译函数
function Translate(str, RequestLanguage, ResultLanguage: string): string;
const
BaseUrl = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=';
var
Url: string;
jo: ISuperObject;
req: IXMLHTTPRequest;
begin
Url := BaseUrl + ToUTF8Encode(str) + '&langpair=' + RequestLanguage + '%7C' + ResultLanguage;
req := CoXMLHTTP.Create;
req.open('Get', Url, False, EmptyParam, EmptyParam);
req.send(EmptyParam);
jo := SO(req.responseText);
Result := jo.Format('%responseData.translatedText%');
end;
//英译汉
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo2.Text := Translate(Memo1.Text, 'en', 'zh-cn');
end;
//汉译英
procedure TForm1.Button2Click(Sender: TObject);
begin
Memo1.Text := Translate(Memo2.Text, 'zh-cn', 'en');
end;
end.