uses System.SysUtils, System.Classes, System.Net.HttpClient, System.Net.HttpClientComponent, System.RegularExpressions, System.JSON; function Trans(const word: string): string; var HttpClient: TNetHTTPClient; Response: IHTTPResponse; gi, ig, token, t, url, translated_text: string; flg: Boolean; from_word, to_word: string; tokens: TArray<string>; data: TStringList; jsonResponse: TJSONArray; jsonValue: TJSONValue; begin Result := '翻译失败'; HttpClient := TNetHTTPClient.Create(nil); try flg := TRegEx.IsMatch(word, '[一-龥]'); if flg then begin from_word := 'zh-Hans'; to_word := 'en-GB'; end else begin from_word := 'en-GB'; to_word := 'zh-Hans'; end; gi := HttpClient.Get('https://cn.bing.com/translator').ContentAsString(); ig := TRegEx.Match(gi, 'IG:"(.*?)"').Groups[1].Value; token := TRegEx.Match(gi, 'params_AbusePreventionHelper = (.*?);').Groups[1].Value; tokens := token.Replace('[', '').Split([',']); t := Copy(tokens[1], 2, 32); url := Format('https://cn.bing.com/ttranslatev3?isVertical=1&&IG=%s&IID=translator.5027', [ig]); data := TStringList.Create; try data.Add('fromLang=' + from_word); data.Add('text=' + word); data.Add('to=' + to_word); data.Add('token=' + t); data.Add('key=' + tokens[0]); data.Add('tryFetchingGenderDebiasedTranslations=true'); HttpClient.CustomHeaders['User-Agent'] := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'; Response := HttpClient.Post(url, data); jsonResponse := TJSONObject.ParseJSONValue(Response.ContentAsString()) as TJSONArray; if Assigned(jsonResponse) then try jsonValue := jsonResponse.Items[0].GetValue<TJSONArray>('translations').Items[0]; translated_text := jsonValue.GetValue<string>('text'); Result := translated_text; finally jsonResponse.Free; end; finally data.Free; end; finally HttpClient.Free; end; end; procedure Main; var word, result: string; begin word := '你说你,想要逃,剩下空心要不要'; result := Trans(word); Writeln(result); end; begin try Main; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号
执行时间: 0.036110162734985 seconds