原文! L% t1 F: Q, b6 w! @1 @$ G+ r
http://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx
/ _) G5 Q D7 O9 ^- N/ f$ C6 }! p" e/ T
Here is how you can translate a Text using Google's "Unofficial" API's.
9 M" I6 F' S; W9 R! C$ SThe URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}0 I- L+ ^+ K: U6 a, U
[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., k$ Y4 D7 L% U0 Z: s, Z) Z
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.$ s3 m3 B* `. b/ T1 G
/// <summary>
) n1 d# j! e5 ~2 k: |0 A9 h- z; ~5 o% [- N/ G
/// Translate Text using Google Translate API's- I. C% G, U2 F2 ?/ J. X q+ c
- z1 | L9 p( n/ J0 V. T/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
+ K) \) e5 R r3 K" S- W$ ^4 l0 J( K/ L# v6 i5 A
/// </summary>& F. V6 H1 x! T( H2 Q
+ G% Q8 N( A& g
/// <param name="input">Input string</param>
- X2 A7 Y; T7 {( u; C! r1 _2 I" Y B* W
/// <param name="languagePair">2 letter Language Pair, delimited by "|".
+ E7 K3 G) P$ J3 s/// E.g. "ar|en" language pair means to translate from Arabic to English</param>6 T0 c6 }; Q' u) I
; b0 G2 ~* E7 a, S& A/ E/ n, x: d/// <returns>Translated to String</returns>
" H% e2 s' X0 p3 S/ S! Z. [8 ?$ \/ E0 b; E! m7 n
public string TranslateText(
+ m- Z1 b* k. d; v: M
9 T6 l: `+ Y: }6 C7 | string input,% T7 m* t8 Z) r* P5 t& c3 K8 B
1 _3 g/ @$ V" s1 g% K2 y, C2 c
string languagePair)
N: R' Y: r w' I; e$ P# V" n0 D. w) q3 v b
{" O2 v6 a7 F$ I1 `3 H% i( k$ m5 S
( k. ?. B4 S$ \5 v& Y* s
9 S! T; l; K+ F: M2 v6 a: }* I8 M ?' Q5 |
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
, ~9 x0 x! i! L* N2 y& _) q; S9 }- ]/ ]' f o7 J, `2 J1 C, A0 Z
WebClient webClient = new WebClient();" k2 r. B6 z& }) h
( Y( h W5 N9 b& Z: ~: x: c) y$ ?% C webClient.Encoding = System.Text.Encoding.UTF8;9 n. Y! ~; W. \2 [
' E* a+ H! X9 E w
! a2 ?/ C& s l j! x& N
8 P% H, |8 C% ?, _: P9 V/ n
string result = webClient.DownloadString(url);2 L6 h' q" H5 R: W; ~7 d
$ l) n' W. K. X+ B( d& [; j
result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
- H+ s8 @# w+ U* x" [! e8 G3 [
( o* m; s( E) b' J! J result = result.Substring(0, result.IndexOf("</div"));
0 ]: R& R8 I3 a4 O. z) h
b4 e' |7 f' o0 j
) P: b) @% g3 a& F+ |, f; [8 y4 f5 A! j7 C5 M: p4 U: O( d
return result;
# M4 Q1 q, J6 L! ]: g5 ~' I% r" J& p4 u# L/ m
}
3 P0 x2 I" Z3 q m) v, a) _7 rMore details about this Unofficial Google Translation API can be found Here |