原文8 F- h5 E8 n3 n6 w
http://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx
; U. a2 Z* ]! X4 C( F% D6 t- B6 e1 T9 H6 T# V, I1 i ^
Here is how you can translate a Text using Google's "Unofficial" API's.
- E8 H2 K, n/ CThe URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}& D7 t( h6 X. [ J5 O1 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.
: u& N5 `+ b* d1 m" n: l* G4 @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.. ]( s( N; w4 q- y. ^1 h/ w/ y7 a9 e
/// <summary>9 s& t9 n2 k5 O8 ?+ ~+ H3 _/ \
6 T9 m$ j1 q \* s3 }5 R" O* k& P/// Translate Text using Google Translate API's
% E) }; r$ l$ a Q1 w9 f5 A( }; O6 `5 i* O m
/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
! @( m' J! v# Z5 S a* T2 A
9 i. ~( h& W w1 ?/// </summary>- R6 _" i5 W# V: f3 _
0 J1 f/ ]' w, l3 w6 m( L/// <param name="input">Input string</param>4 @8 \5 [6 c+ y$ G. B6 H: y
+ a6 t3 d$ D; M& o8 Z
/// <param name="languagePair">2 letter Language Pair, delimited by "|". 3 U$ x) c% ?1 K- ~3 Q% ?! f. [
/// E.g. "ar|en" language pair means to translate from Arabic to English</param>
3 L6 B" Q9 T( Z' o- ~6 a3 p; i0 z! d
/// <returns>Translated to String</returns>
) n6 l; v ~8 A& `2 R8 y& A; H" w* Y O- S _$ Z# y0 u/ u( W# t
public string TranslateText(
; n' s( x2 J y. `- m n, q/ n# w6 x3 l/ y
string input,- ~; b4 ~1 G8 H: t, }; E. z+ p7 q
7 B i% W0 s0 f2 {7 P! r string languagePair)3 H. U7 A, w. u& H: h
5 K+ `2 Q' J3 j* W4 r+ T: D{
5 x. _1 ~% F% k, L9 c& {, O/ I# b' X3 Y
/ K8 B; c/ x3 }- D- G. j' H
1 D* [( D" a+ t, j8 K3 Y: N& B string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
. ?7 o$ @# _ [9 {# M; q3 Z" g8 W9 c1 r: s) E6 n
WebClient webClient = new WebClient();2 t* Q C0 i; g# Y. T" k3 }
9 ?) Y3 d6 ]9 a- T/ l webClient.Encoding = System.Text.Encoding.UTF8;
/ N9 P0 ?2 M! {
) u& W5 k ?" s7 i; |6 H$ f, |: k7 Y" k1 D1 j& M: H p
( U5 E; H& y+ G. k2 a+ l _
string result = webClient.DownloadString(url);9 J4 P' g: y" W, |
! x& }+ j4 d# p) `- a% W' w) y9 D# }
result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);+ a2 V, a% A- |& a
' k* \: U. r4 ~7 ~
result = result.Substring(0, result.IndexOf("</div"));
; `5 [; [( _& h- K. q# Q# H) u) M' z4 I4 K0 G
3 } o& W6 t' p# J! {1 Z" w
4 f- I. m# x4 n. j
return result;
, F* r% c2 B! y3 p, L5 x
8 Z; @# H3 O" m$ ?" |. x' i}
. f* s6 v# M% N, K8 QMore details about this Unofficial Google Translation API can be found Here |