原文
) ^+ L9 L% ]4 |9 e& Uhttp://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx. p+ D8 S. J n- \2 W
/ `+ U9 Q1 E( g2 R! m0 `
Here is how you can translate a Text using Google's "Unofficial" API's. N+ X! X$ J7 b i
The URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
+ {6 B9 u) f# q6 F[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.
+ H2 t; b3 I' C, H& C' {1 S' 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.
+ Y" a/ Q/ R/ N& D/ f/// <summary>2 d, d2 t% N1 V3 s4 ?* `
# z" n I+ d! @$ Q2 [4 x) g/// Translate Text using Google Translate API's
) G: j" J4 r, v3 J |; G2 H
- i3 Y" l- e5 x% G- w2 ~. h/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
! L) S1 |5 J* U7 d/ h0 K5 A
' i6 m$ V1 h' m4 w ]) Q) Y) {/// </summary>
1 U `0 I; N' J( f; H2 b, H* G* b- T' h( ^2 m
/// <param name="input">Input string</param>
" o+ A2 ?- l& n. H! t. I5 w5 s- g: u y- ~( n$ ?
/// <param name="languagePair">2 letter Language Pair, delimited by "|". / }' _0 |5 S E- T# F$ e
/// E.g. "ar|en" language pair means to translate from Arabic to English</param>( e' ~) t/ x3 k& O7 |
# R' @( ?" A- ]3 ?) s6 k2 g( F
/// <returns>Translated to String</returns>1 z j8 ^8 A4 e* B+ p* g9 V( _
: r) j2 h. [' {/ P
public string TranslateText(
8 p. U [! c! b# Q( ]2 S. U0 _( j2 ]
string input,4 c( p b7 n6 z5 w
; ]- l- H6 A; u) K4 T
string languagePair)
) k+ c8 R: k) j0 a* r! F' o$ c7 h. h7 v+ z
{. Z- O" x; E+ `$ u! d; W1 W$ C
' |, l$ v3 n5 K+ L' h4 B ^" V
# I( K7 f. c3 I8 x! {! P" w/ I
! w* j" a$ Y: Y: g- Y/ C string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);& `9 F$ s0 I( h9 ]( n
' F# r! Q E1 c ~+ I WebClient webClient = new WebClient();
" R9 e \$ I* w! A8 n N; p# [5 z0 B Z/ q/ h
webClient.Encoding = System.Text.Encoding.UTF8;
# o! l, v4 b. M/ b9 H. \4 Z& q2 ^5 G! j1 k8 i2 ~
& R& c6 H. i$ F' B- U: K" ^, K& B! t( n8 Q, M
string result = webClient.DownloadString(url);3 Y6 L8 o0 A T$ y
# D% V2 f! A" }4 `/ {& n0 @1 k
result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
. i; b' W3 t( C- |9 {- Q& w: s& a! N+ h
result = result.Substring(0, result.IndexOf("</div"));
% h7 _- h9 b" k6 q
/ }/ c9 {$ ?% e. V9 d
S9 D% Q$ E1 Q- B
( j. |# H( W7 q, }2 }4 |8 c return result;5 L+ @0 V, d, S, g, B
0 n q+ \. @0 ^6 f2 _. f/ y}! I- b' ?; P: n, n5 X' {
More details about this Unofficial Google Translation API can be found Here |