原文
" H- E$ m4 f% P$ R# t# b, zhttp://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx
* z0 q; z) W. W" @7 C! a1 c# k+ A7 _1 N5 A7 X6 f% c# m; g
Here is how you can translate a Text using Google's "Unofficial" API's.* Q/ L1 ?5 m8 ?1 J# ~
The URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
/ z" E1 C. h0 h( 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.
) s& G$ R- M6 X4 f3 b! @9 d5 U! LBelow is a C# function which translates, scrapes and gives you the result. I am using String.Substring function but you can use Regex too.
% Y: ~3 B6 R" H/ i4 g/// <summary>
5 u* f. k; @& ?# }: ~& S: o7 p
( A: r6 V. ?+ O9 R( p Y5 `$ X/// Translate Text using Google Translate API's
7 s" q2 \ ?" o/ [, Q2 [( r, q9 A1 a: x6 U% ]
/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
* Z7 W9 `% b3 K4 a5 a. O2 p+ k4 U5 {7 e# j. v
/// </summary>! H ]; x8 r9 m' O8 L: u
* @6 u8 O" `8 x5 M4 j; R/// <param name="input">Input string</param>5 `; k. v, l" P3 ]1 ~
( u1 q7 H. Q; S. k
/// <param name="languagePair">2 letter Language Pair, delimited by "|". 0 ^2 x, n, H' x* X y5 g Q" V
/// E.g. "ar|en" language pair means to translate from Arabic to English</param>, z1 ~9 w- V0 Y1 g# x$ v
' n; g! Y* D; h' l
/// <returns>Translated to String</returns>4 `% a. Q) a! F
3 z9 g' B& G0 b9 {) s
public string TranslateText(! l0 f& W# y, I" ^! m7 C
" f$ P$ h5 J: |, `+ n, N8 Z
string input,, U8 P6 C; p; F8 _! j5 y! _
8 w& q6 j' F, G( L7 j9 V string languagePair)1 p6 _) ?# i+ A# s
; h! j" F2 H V
{
. [7 @- L/ O2 I( O% e, J6 p& j9 v4 F3 z* Y: X* O
# w5 k) V/ c" L3 o* ]1 c
7 w" Q1 K# K; s2 p! G& o% j/ Q string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
) F" I; E5 n* n, \& j4 A6 f. _' i# ?) h
WebClient webClient = new WebClient();
. O) d3 t& O7 v8 a
, w- {' k( i, n$ h. d, O webClient.Encoding = System.Text.Encoding.UTF8;( S6 {0 }0 u" ?5 @) c* h* H5 U& N& k& ?
8 U$ I3 I/ w' b) D
2 B/ e; T9 a4 i7 p7 l2 y. M" n/ M! j
string result = webClient.DownloadString(url);
3 o j: G1 E2 Z4 r3 E9 b0 S
3 a; M/ c* l/ l result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
1 x7 F, @0 v2 ~
8 ~! d; ?; H' A$ Q- u$ n; s result = result.Substring(0, result.IndexOf("</div"));% c: d# t! e$ d
a- H' T; R9 K+ v2 V
% [3 g% T' i8 v2 o8 M( L `
3 ]4 h8 s$ D2 K3 A; Q! Q
return result;1 E, d( |% _( t/ J& G9 M
r8 G# J. x. G: z- L2 C6 \
}" u7 N6 s' w! p7 v6 R& \ {4 ?
More details about this Unofficial Google Translation API can be found Here |