原文
8 z. z5 ^4 W( c0 Y: Uhttp://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx( ?; V( M0 N) G. l. C0 J' Y
, A) H8 @ B! V1 } @# t- F8 m9 FHere is how you can translate a Text using Google's "Unofficial" API's." c+ p P2 M, F. t$ y% \5 Y# [
The URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
J/ @7 c$ l% P* L, t1 A2 {[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.
& ?4 S2 l% Z D# Y5 [2 T [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.9 e) t- n* Q. n1 }
/// <summary>
8 V0 P3 J/ [2 H- M7 w0 p2 |2 x- e1 a
; X* S, Y `1 F0 Q) A/// Translate Text using Google Translate API's, x4 R; {' R3 r0 m7 u2 N2 }" }. u
. f- b" y5 d+ @& n8 Q
/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
" O1 c& |# U& s' A+ P, \8 c' [- i1 ` _' d
/// </summary>
$ H u% |& y4 Z* u/ f+ q
/ i% Y# e5 W6 Y3 B% s* a/// <param name="input">Input string</param>" \2 c0 @) _7 o* h7 F
) V3 [- W$ k: G' G& p. O2 Y; O
/// <param name="languagePair">2 letter Language Pair, delimited by "|".
. H# n2 P4 |8 p! w6 v% @: S/// E.g. "ar|en" language pair means to translate from Arabic to English</param>
, m9 K! C9 g0 L+ z6 t; ?2 `9 |3 r/ U; t: p0 \
/// <returns>Translated to String</returns>
3 f" {* m. R! g! Y/ e- j4 w) m; a7 @7 h, ~2 J
public string TranslateText(
1 f/ `6 c% X& ~) W* z3 w; v; Y3 X% C* t" y* V Y
string input,
8 W0 C7 ^% T$ O. b9 K. l# O
: q% I Y; g# h6 y string languagePair)
! N2 p6 @$ {' U! Y6 y+ B' a( n9 o
5 H- S3 D- y N- F" i0 I- V4 T& L) N{+ z" G; S+ i% |) M4 K. e7 }
) g7 V) ?, |6 P/ s9 R; X( r6 L: t: v- [7 ^# w8 W! [3 i9 b
) b' u* ~# K$ c' c string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);1 R, x* A- w8 ?
, i, V$ z$ N( [4 y: t! _
WebClient webClient = new WebClient();" l" a X5 }$ Q: u% ^
: z2 G$ m- e" a webClient.Encoding = System.Text.Encoding.UTF8;
1 g/ ]8 l0 }/ {: E% f6 [* R. O" x
O6 x% J6 g% B S
0 V8 ]8 }3 }# L( {' X! q0 E string result = webClient.DownloadString(url);* S* ~& q: r3 _ x- U8 K+ x
3 B1 A7 }! M! y: Q& z# W: L! C result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);. Q" c( ~) K' e; F
$ M2 _/ d4 q/ p9 }9 P
result = result.Substring(0, result.IndexOf("</div"));
4 q/ z. o; U5 f" }9 Y2 R/ t- A' [8 _+ g3 L8 L) A8 |) E9 d
! |- z( r5 S5 b5 H, W( I
( p0 Y9 V, A4 t& s/ P+ a
return result;! Y! v' l5 C% F/ m( U$ |' y
$ \, C. A$ N6 Z
}
) R3 d( ?3 F/ x( H) P+ A5 WMore details about this Unofficial Google Translation API can be found Here |