原文
* ^8 X% u, X hhttp://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx
+ w6 j- }0 t; D8 q X6 X$ y
$ U: Q' p' `/ \& V4 J+ w3 w5 jHere is how you can translate a Text using Google's "Unofficial" API's.2 M; X3 D; m$ k1 d& n% o
The URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
2 T' {: `! Y+ \) Z[li]"text" is your input string which needs to be translated. [/li][li]langpair is the language pairs involved in the tranlsation. E.g. "ar|en" means translate from Arabic to English.[/li] The result when you browse to the URL is a HTML page. You will have to do screen scraping to get your translated text.; h& Q' n7 W/ q% H9 X9 m& M) w4 K
Below is a C# function which translates, scrapes and gives you the result. I am using String.Substring function but you can use Regex too.' W; c$ g& _3 V
/// <summary>& z+ q# u4 F' g# s p/ n* a3 B
, Y( ?' L+ G/ R, |; Q/// Translate Text using Google Translate API's
% y' H0 l k1 `$ M m1 \- n: a6 U2 a! F
/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}4 l9 w8 d; i! D G0 o3 F/ g' @
" X6 m4 C& o, o" v8 o" Q/// </summary>
# E! R2 W5 L( k! q1 h7 x6 e
( N' H! {& v1 c# Z% X( Q3 t/// <param name="input">Input string</param>
% N" C, |/ M" b5 x' p+ t4 B; `+ L8 e8 r# x8 H
/// <param name="languagePair">2 letter Language Pair, delimited by "|". , D F" b8 O, N8 U
/// E.g. "ar|en" language pair means to translate from Arabic to English</param>$ }: ^( {' R8 y' P' m) u
* R2 W& \" F! w- _/ D& b( t4 v/// <returns>Translated to String</returns> J+ P% n1 }; p6 q% T
* z5 \4 L, t5 R6 _# e. t" _
public string TranslateText(/ l7 \4 F3 ?( _+ B
3 @* R6 @8 A: I9 h1 r) _- F8 C string input,$ H4 ?* r" D, I8 |" ^
6 z. G6 `' ^ y9 J7 M8 _
string languagePair)
3 P4 N; @$ O& x2 l* o% |3 E; k6 e1 N5 x& G
{
9 E |7 g6 ]) M# _; t d8 ~8 Y3 @ H- I/ L( i h' x
/ f& X4 f! R. y
0 F. H$ p: `. L# q. X q* b string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
( D$ N# `8 z% t8 p4 d4 N/ w; t
8 d. R2 s4 D# p# ]+ t( c( U0 x WebClient webClient = new WebClient();
" U0 \6 X' p) \! \# \+ l& O
) A4 Y* e$ r3 ~9 }+ p webClient.Encoding = System.Text.Encoding.UTF8;6 L5 [* [: ^+ }; Q0 O% v
1 X6 R3 e/ L( U, v+ {+ F D: e+ I, z- N+ V+ v8 i- L5 ]
! T' ?, B, H1 p( j* N* ?0 A string result = webClient.DownloadString(url);
9 q0 N J3 k5 u5 c/ }/ o8 n, Y2 D, P( X) O2 s; E* e
result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
6 A9 ~# f- r3 @$ p. i8 C
X* Q; c9 a4 t9 F% @ result = result.Substring(0, result.IndexOf("</div"));5 h/ t' v* X5 |) ]/ M
% R9 L; N9 H+ u* Y, n
2 o# j. w5 `9 g' u! R- D. r* p' G: m# S; n* d5 c8 ?8 P; V
return result;# ]2 j0 j: `/ G8 }% a$ Y
; r5 k2 ^; i8 ^/ G
}, ^9 g5 ~* u' ] n! g
More details about this Unofficial Google Translation API can be found Here |