原文
, V# E8 `* n4 k3 A0 E7 v- I6 _http://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx
\2 ~% R7 ]! D7 h& W7 w$ f+ l( { b' ~7 r& k( U& j
Here is how you can translate a Text using Google's "Unofficial" API's.4 h2 g8 F& T# k, K7 [
The URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
9 ?( W3 D8 u/ U/ x' M[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.
- S* z, v0 ?: l5 C: 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* d! `/ u4 |' Y0 P P' x I$ X
/// <summary>* g. O$ @" R8 ]1 A& B2 `2 S
+ a) f0 l* J2 s7 F P! g2 Z5 |/// Translate Text using Google Translate API's
& H# W2 }1 B; I7 I0 u1 z
* p* i( E( V g2 X" f: C/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}4 [' B; r Z6 V
9 f) S) m2 R6 G6 o$ n& m( T/// </summary>
! h# F( a v, ?% c
' K2 ~0 b l' p# r4 p3 V/// <param name="input">Input string</param>
' |; }5 D+ \+ |: P
2 F) Z& Y* ^+ G/// <param name="languagePair">2 letter Language Pair, delimited by "|". $ M& {3 L1 x, g& N! z" B
/// E.g. "ar|en" language pair means to translate from Arabic to English</param>
- ~$ D# P$ @& X/ n, ^! p, B# O$ F9 U
/// <returns>Translated to String</returns>
2 u3 T# I9 E" P* k6 U9 M
0 f$ T1 w, }3 B" g0 xpublic string TranslateText(
' Q: i7 w' L# D: g+ `! c9 `
* c9 M; J& {# t( p) V" P K2 N string input,, K- p2 V2 Y# g I& l2 Q
2 \, y% q7 a5 B) C; \
string languagePair)
% X) m% O* h8 m( u2 C- s. R/ o" G/ w% v( K; U! ?
{5 J0 l- x9 I8 w* d3 M
" k: Q" ]* H" i. R5 d4 c# h4 o; K7 _9 w/ \# e
+ F# `) G3 z" o string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
( _# V# ~$ d j! b$ P5 x9 v2 L k4 ?5 H$ U# p
WebClient webClient = new WebClient();
- }; J$ n: b9 p* i8 I R6 B# m. Q1 |; E' Y' T" P1 \
webClient.Encoding = System.Text.Encoding.UTF8;8 i$ L) I& _4 Q, P* U u' K
5 l% A& I, J4 r
3 b" G" O2 \/ Q5 C- Y6 g0 z X- P* k& ?: Z9 `- G- k. f* V
string result = webClient.DownloadString(url);
0 ~! w! f" Z* _ _& R) b+ M8 D# U& t1 h: g2 \, v$ N* G
result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
& o7 K9 Q$ b& F; c* p4 ~. t1 G8 f4 M, o; \" B
result = result.Substring(0, result.IndexOf("</div"));. B q2 H7 i8 j5 t
2 _8 Y3 [4 F% b1 G. d1 D' y$ Z" D3 B1 O
+ H+ v$ d ? v6 H* ~) P7 n9 E9 N return result;
, u$ w& \8 A* L0 E
! q% o/ `/ \" m, O; }; R, ]}) K0 N2 P- K; ]
More details about this Unofficial Google Translation API can be found Here |