原文- u" @, E: v$ H4 Z- l4 F# ^# i
http://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx4 j: Q( {' e9 N4 ^+ K& ?' o
" u/ D$ H/ _5 W+ _, I
Here is how you can translate a Text using Google's "Unofficial" API's.
) _; C7 k4 c7 qThe URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}' ~+ q* F& p2 l
[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.
' o; L! h- [3 \/ o8 g) }1 G4 CBelow is a C# function which translates, scrapes and gives you the result. I am using String.Substring function but you can use Regex too.! \( ~" v! W5 f8 q% D J
/// <summary>* K* s% ]+ P; t6 i* k+ H! L; e9 g
. e5 ]0 M2 J- C8 ] u% {" J1 L( `
/// Translate Text using Google Translate API's+ A% ?$ D6 C! k
: _7 k/ A+ i V7 U# E/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
& f6 Z3 L5 c }: `2 ?" W+ [/ k* o+ }% ~7 t' w6 H4 `
/// </summary>
9 s) c, Z3 C7 C, r i7 o8 ~, V N" Q2 q8 Y, x8 s
/// <param name="input">Input string</param>! L, u* N6 K M. C# f
" [! g; k% w1 P } b7 r/// <param name="languagePair">2 letter Language Pair, delimited by "|". & V$ a/ i0 m# s1 [8 K7 T6 e
/// E.g. "ar|en" language pair means to translate from Arabic to English</param>
, v+ U; M5 l0 i$ ~' g, p
/ t3 F, Z7 V2 m& L, p) i/// <returns>Translated to String</returns>
, s& d( |$ T5 I' Z+ N3 {: s( s/ o
1 E2 R5 j8 y1 R) Z8 h; vpublic string TranslateText(
! H9 l7 | {( u- b( V# O* j1 C9 \" r0 A( G. W2 G( Q# m; f
string input,
; B" ~% Q8 Q- @2 _$ g/ ^2 @: h9 e) z6 l0 _
string languagePair)
% [1 u7 @7 C; J; j [1 w
; T P+ ^# H8 C! c- j{
: Y3 z; o v' M3 w) G! h2 a2 t; X4 k9 I3 c0 ] R- o( y
- n1 A7 @ p3 W* d" U1 ?$ R# }. P% T" s& `$ m/ ]$ W! e
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);- V" N! @$ V! j, {. H
6 _, m6 H2 k5 n WebClient webClient = new WebClient();
6 X3 r3 J- n' R6 F% d1 g# s; k4 |$ c3 y e5 U% ]! }) }1 e" V
webClient.Encoding = System.Text.Encoding.UTF8;
: u7 R) x' `# t3 _& a" t9 |5 S7 Q; ~# |* \) h! p3 q' d2 Q
* ~5 a& ]. G" D& W. V/ v" `
' x. Q: l1 a0 Z$ A9 {# R" B string result = webClient.DownloadString(url);9 c. F% _: `5 Z; }
% M% y( H$ ^. T. U4 n+ b/ a, `; W4 {
result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
2 B0 P3 N7 |; P' i7 s: W. M* f/ s g1 ?' |& K+ _8 f1 A% b
result = result.Substring(0, result.IndexOf("</div"));
* H: r" `* f" ^1 U. Y$ y, A( i: T2 H2 I
' X+ V+ R0 q$ v1 G( r
0 _( u$ v: I- H/ k% Q- U' L, F0 A return result;
j9 r9 X4 F# q4 R; E+ H& j4 ~0 }: }5 O6 F+ i2 d3 |/ `! s1 E
}
; o; n4 l$ @) X" k0 cMore details about this Unofficial Google Translation API can be found Here |