原文
# Y3 h) V( F4 ?8 w) rhttp://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx
. B8 v8 Q% Y( V; n r6 B, ]3 ]
* E2 y4 V+ M+ e) OHere is how you can translate a Text using Google's "Unofficial" API's.
) D/ B- M+ h; ^' D( mThe URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}8 N( p5 I, x& @$ l& f. \1 X
[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.
' C% D( D! @0 }4 ABelow is a C# function which translates, scrapes and gives you the result. I am using String.Substring function but you can use Regex too.& P, i& a$ P, {* g# _* P7 c6 N
/// <summary>
; F0 U2 T1 x- u1 z. E' d
: J. D% Z7 x9 F0 z, D* S/// Translate Text using Google Translate API's
0 _! ?8 i0 Y* C4 q
5 Z) F+ C& ?/ Q, N- |- x7 C/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1} X- q/ F( v8 D! w7 \. C, L
1 [% U, o4 |3 v9 a
/// </summary>! `, C4 e2 A/ F8 C7 a! _* l
1 r' q6 s5 z$ k
/// <param name="input">Input string</param>
; ~! f. f, u* x8 K' G& p
4 H" e$ s3 P- N) R/// <param name="languagePair">2 letter Language Pair, delimited by "|".
7 Y& `* b! M& {& P/ ?9 T9 I/// E.g. "ar|en" language pair means to translate from Arabic to English</param>' d* B" g8 P, ~! X6 T C
( S) U" s! F9 I8 e
/// <returns>Translated to String</returns>6 P& h, s; p8 a' S, u
# \3 A6 w! t2 s- _2 s
public string TranslateText(0 \% h; M D, P
( Z6 j( y" B. t% g5 b3 u string input,
5 g2 k# J5 |& Q6 u2 W* e/ P s' {! h n8 R9 L6 R( R3 a% P/ k
string languagePair)
8 V7 J) N- ?9 M6 @$ q# x: p1 E8 `4 |7 v/ m7 V7 C, `1 L; S, g" O
{
6 m8 h5 Z* r6 S2 y+ O
0 {) E( @+ t$ F" E- S$ d6 R" o* S
) J2 _2 O) v. R3 K1 w9 F- A
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);# Z+ I. Z* X1 J! ]& K
9 ?& X4 }8 [% G% N( S( i/ r
WebClient webClient = new WebClient();
: e9 S* ]! `& _0 e8 q* M+ c! ]0 C3 q m# ]3 e a* a$ t/ s
webClient.Encoding = System.Text.Encoding.UTF8;- n% n( R9 B5 u2 s$ R
9 O* L5 ^4 j( t1 p& L
$ |. t2 M$ D) {
& k% y2 G8 A6 l string result = webClient.DownloadString(url);
7 ]) I Z7 @! G, G# k: h" C5 s( r+ O0 P6 v, x5 c2 }" l6 N( t
result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
4 [5 V- Z5 d6 P: i8 E: C2 W2 p( ^
result = result.Substring(0, result.IndexOf("</div"));% q* j; @% L. N; |
9 J) q8 i& |! P0 S) V% {( O$ U8 Z$ M, R
# {0 E3 \9 g/ C+ `5 y% b( `
) y9 _! s& v( c, z7 G( W/ h return result;7 b% n* Q, l- F% K& [* @; D2 h
9 o$ I5 m; `/ b}
0 k2 E$ K1 ?2 cMore details about this Unofficial Google Translation API can be found Here |