原文, i( w3 V8 q( b+ f+ Z7 U' k0 L
http://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx% D$ ^+ x6 N( y0 b: r; W$ X
4 e. y% A6 u! R' p2 u2 J& Z
Here is how you can translate a Text using Google's "Unofficial" API's.6 w E: F3 n) H# \5 I6 c% W1 e
The URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
- Y# g6 k2 n! E1 ?( h' Y8 M' L) |) C[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.
2 m( r {6 V, r- T& {% \6 e3 B* t2 ]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.% E) {/ r. H- I. L4 }, i
/// <summary>9 O' l; S5 f* |4 g
6 x+ ^4 a9 p% G! m5 [$ d% o/// Translate Text using Google Translate API's
3 R7 w3 Q% ?1 l( }" O( ?3 H: K' ^1 n
/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}6 B, p1 {8 W% Q% c
( P3 w1 e# M; Q4 n/// </summary>9 A; @( `' _$ m8 G
- {3 Y A6 b1 x+ U' ] x7 L
/// <param name="input">Input string</param>
8 _/ `0 e9 C. p( I# j
# [7 w I* o6 y" r9 e/// <param name="languagePair">2 letter Language Pair, delimited by "|".
/ ?# j& Y& { v9 ?2 F$ R4 q$ u; ~3 M/// E.g. "ar|en" language pair means to translate from Arabic to English</param>
; R7 ?; h; z {# c0 G" @: q2 R. E7 F
/// <returns>Translated to String</returns>& H9 k1 @" R% [. G2 c! I" V+ g y
8 T7 S1 T {+ k& [2 ^public string TranslateText(, a$ S0 L" Y+ l! L# m" P
) q Z1 c& @6 D9 r; n1 j$ A
string input,
5 R: L5 |. U# P! K
4 M/ z8 J" C; I' `+ D; ]/ ~3 S string languagePair); I; A, J' ^; f2 U% w$ D" E
) ^& `2 _9 u; B- L* i- z1 y. j& P{ X9 Z! S8 S$ u" V
' E. N B% M R! U+ [! X
0 H& A" z7 u) e9 t
2 u! a7 Y/ X& p' I) g0 ? string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
: U" P' Z% q5 _+ r! j3 h/ S$ V4 F& w0 X+ W/ x
WebClient webClient = new WebClient();, h- I. s% Q0 x
* `) a- w1 n: A# ]! I' u } webClient.Encoding = System.Text.Encoding.UTF8;
( ^* [4 k g; ]; x/ y6 x8 Y. z4 s u4 e: y1 w, o- O% F8 p/ B0 ]
# _6 w' u. Q# ]3 Z( a
9 ?2 Y, c* v- Z3 ^ string result = webClient.DownloadString(url);6 x( W6 n- B+ ~1 x+ r' H6 _
% B( X3 H+ S& o9 _( O9 `
result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
& n+ `' t% g9 c/ a4 G. E1 E! P
7 A! s! f' c7 ?6 `3 r- B result = result.Substring(0, result.IndexOf("</div"));+ x6 z' D) Q! Y3 f, g! W
. }" |. u, W: o* o; A6 `
' H; k* D. I- v. \4 V" U Q& `
, [, Q# m1 o& |" j' C1 }& O return result;
5 P3 e" t! h" D) T* Y
: \" f* L7 R7 N" H}
% b5 G- c( \# Z- X* z- UMore details about this Unofficial Google Translation API can be found Here |