欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 前端技术 > javascript >内容正文

javascript

JSON 之 SuperObject(17): 实例 - 借用 Google 实现全文翻译

发布时间:2025/3/15 javascript 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 JSON 之 SuperObject(17): 实例 - 借用 Google 实现全文翻译 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

调用 Google 翻译的地址格式:

http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=" + 原始文本 + "&langpair=" + 原语言 + "%7C" + 目标语言

返回的数据格式如下, 可以用 responseData.translatedText 简单获取:
{"responseData" : {"translatedText" : "返回的文本"}, "responseDetails" : null, "responseStatus" : 200 }
本例效果图:



代码文件:
unit Unit1;interfaceusesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,Dialogs, StdCtrls;typeTForm1 = class(TForm)Memo1: TMemo;Memo2: TMemo;Button1: TButton;Button2: TButton;procedure Button1Click(Sender: TObject);procedure Button2Click(Sender: TObject);end;varForm1: TForm1;implementation{$R *.dfm}uses MsXML, SuperObject;//字符串到 UTF8 编码的函数, 用于 Google 地址 function ToUTF8Encode(str: string): string; varb: Byte; beginfor b in BytesOf(UTF8Encode(str)) doResult := Format('%s%s%.2x', [Result, '%', b]); end;//翻译函数 function Translate(str, RequestLanguage, ResultLanguage: string): string; constBaseUrl = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='; varUrl: string;jo: ISuperObject;req: IXMLHTTPRequest; beginUrl := 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); beginMemo2.Text := Translate(Memo1.Text, 'en', 'zh-cn'); end;//汉译英 procedure TForm1.Button2Click(Sender: TObject); beginMemo1.Text := Translate(Memo2.Text, 'zh-cn', 'en'); end;end.
窗体文件:
object Form1: TForm1Left = 0Top = 0Caption = 'Form1'ClientHeight = 139ClientWidth = 459Color = clBtnFaceFont.Charset = DEFAULT_CHARSETFont.Color = clWindowTextFont.Height = -11Font.Name = 'Tahoma'Font.Style = []OldCreateOrder = FalsePixelsPerInch = 96TextHeight = 13object Memo1: TMemoLeft = 0Top = 0Width = 185Height = 139Align = alLeftLines.Strings = ('Memo1')TabOrder = 0ExplicitHeight = 202endobject Button1: TButtonLeft = 191Top = 24Width = 75Height = 25Caption = #33521#25991' -> '#20013#25991TabOrder = 1OnClick = Button1Clickendobject Memo2: TMemoLeft = 274Top = 0Width = 185Height = 139Align = alRightLines.Strings = ('Memo2')TabOrder = 2ExplicitLeft = 312ExplicitTop = -8ExplicitHeight = 202endobject Button2: TButtonLeft = 191Top = 72Width = 75Height = 25Caption = #33521#25991'

转载于:https://www.cnblogs.com/del/archive/2009/10/28/1591380.html

总结

以上是生活随笔为你收集整理的JSON 之 SuperObject(17): 实例 - 借用 Google 实现全文翻译的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。