原文
; |! f- R/ Q% K8 Ghttp://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx+ h$ r$ m# v; G ?4 R
* Z$ w# E, R U, f0 {0 @Here is how you can translate a Text using Google's "Unofficial" API's.
7 u% o! |# V; T" F# v3 B% eThe URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}( N v* ^, Q& U G- l) Q! A1 V! E
[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.
, T6 p ]0 F, x; e/ F3 @; RBelow is a C# function which translates, scrapes and gives you the result. I am using String.Substring function but you can use Regex too.. C# D; }! _9 A, p
/// <summary>6 k9 {: h4 s7 _% ~& J; k4 F
+ L* K9 F$ W, a
/// Translate Text using Google Translate API's1 s& G5 | f& F! W
A# D( |# r7 |+ D6 b/ q/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
: e; t% G: U' O9 @$ o$ A4 V- u, d
/// </summary>' B1 Z. c' }, N& p
6 Z& F9 X0 w- Z5 y' v) p
/// <param name="input">Input string</param>
, o! @, \: @4 q
: o6 c( ^4 s! Z7 p9 C/// <param name="languagePair">2 letter Language Pair, delimited by "|".
6 X3 _! U. \ s/ b. T/// E.g. "ar|en" language pair means to translate from Arabic to English</param>
5 Q+ U. e6 b7 |! v0 ?6 |6 z) q, m4 Q0 `9 ]5 X
/// <returns>Translated to String</returns>8 T0 v: [0 \& a/ z
/ X. P& H! ^4 k: [# v3 }
public string TranslateText(
' i, _# U( n1 s) T1 F8 v% r# k) ?+ Y: _( ]0 m5 [
string input,
0 l6 a3 X$ Y9 S
v1 G2 d* Z' e string languagePair)9 _' C" p' X! J; }$ C5 }% l+ c
& r. r6 O5 g, L+ k3 l{
1 b' G' u* Q o6 |: o) e& e I! }, X( x2 m, k6 g& y) D
7 _3 I! o; ^- F& Y
: g* G! Z) u: k8 y! k- ~
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair); ~) M7 d' [% C2 j2 S5 d
% F0 X& u9 x+ q5 @% I
WebClient webClient = new WebClient();
/ w* ~/ O( J& S. t" K" C
$ t0 s: l7 R8 Q% V) x% G webClient.Encoding = System.Text.Encoding.UTF8;
7 D" L6 ]3 m& J* V+ [
9 s; j2 ~1 P9 D, S' P. H) D3 U
8 a! ?+ S4 u. q& p, g- b' \& w& x% b3 k$ J& w! i; r
string result = webClient.DownloadString(url);! Z. T4 j7 f% F+ F! S& t
0 o7 D3 g& k& h4 z! [9 I. a$ s, F5 ^
result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
7 A8 j( b. H m X: x0 X: C, _$ r. f! D0 H9 R% w1 }9 H8 T8 w
result = result.Substring(0, result.IndexOf("</div"));
5 Q6 D0 K* z/ r ^ D' G6 a R2 d" ?5 i' |; M+ }
. U2 L! o7 h5 N: U
. |) B; ~; p6 U return result;6 ~* G) Y: G4 h8 W( T+ n
/ Q& e: j; W0 l3 g$ m+ H}
; F8 U9 i0 I6 j8 }8 n/ }1 AMore details about this Unofficial Google Translation API can be found Here |