冒险解谜游戏中文网 ChinaAVG

标题: Translate your text using Google Api's [打印本页]

作者: shane007    时间: 2010-5-21 22:10
标题: Translate your text using Google Api's
原文
( O  R# p1 `. s4 p# v! C! Ihttp://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx  q9 H( J+ M6 u0 N7 w. ?. R5 d
8 @) q7 Q7 M  L( b& H
Here is how you can translate a Text using Google's "Unofficial" API's.% N+ q3 u1 a: e2 p
The URL for Google Translate is - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}, m0 |  H- k- n4 b* u
The result when you browse to the URL is a HTML page. You will have to do screen scraping to get your translated text.
! E5 v! }/ c& q% m7 ^7 ^4 f$ ]6 kBelow is a C# function which translates, scrapes and gives you the result. I am using String.Substring function but you can use Regex too.( t' I& U. \% M( T: p
/// <summary>
4 T( ?! }- Q- k4 d1 d$ e

" t- p% @. E8 I: z+ D/// Translate Text using Google Translate API's1 k3 j6 D( Q2 X( }/ H
& w1 _/ n7 R/ j
/// Google URL - http://www.google.com/translate_ ... =UTF8&text={0}&langpair={1}
9 I# g1 ]1 o. o

+ d( O2 c( O/ U3 u* V- z/// </summary>2 b  }- D& O0 s& t. p
% @& g+ x& Q: a* c4 I+ U. z# e
/// <param name="input">Input string</param>
; F) ~3 L9 N& p5 T2 a3 c
3 j+ M$ i0 s  s5 i& |
/// <param name="languagePair">2 letter Language Pair, delimited by "|".
: T& P4 B3 q( Y3 f8 F4 E/// E.g. "ar|en" language pair means to translate from Arabic to English</param>
% c7 V- S9 t8 e# w) O5 q
2 q9 X3 {: u* b7 C3 |
/// <returns>Translated to String</returns>( \; g) u) A3 M1 }

8 V2 z* `! k: i! spublic string TranslateText(
+ ?& L/ X# h8 X% k9 K

( i, Y, g- L5 t$ V6 L* D    string input,; f1 l+ ?/ X* d. i
2 s0 ?8 W; S7 R
    string languagePair)
) k9 I  a0 }" Y) U
" v" x2 B2 j' e, H# H6 Q& K
{) z* s9 n3 G# Z

( j# R5 X9 `% l( y% `6 n) a8 R
4 |% y- E) c1 ]( v# x- K- n! q

3 O/ d/ m) X4 U# u7 g3 k5 }    string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
' n* B2 H8 d0 E5 F% E- @9 ~% y
" N7 j1 ^7 O& X% j4 M+ x
    WebClient webClient = new WebClient();
8 O+ V0 O4 q5 v8 u3 o0 Z6 Q
" _. ]( Y: A5 U0 B: Q% S
    webClient.Encoding = System.Text.Encoding.UTF8;1 @3 b$ P. b* \; m7 l$ b- U8 x

5 c6 s& q* o# Z
' E- g7 j2 j! O% c- F
( N; H9 S1 |; M8 u3 A
    string result = webClient.DownloadString(url);, f# A! [; m' [1 E1 D

; M4 C* d4 O/ ]1 T, I    result = result.Substring(result.IndexOf("id=result_box") + 22, result.IndexOf("id=result_box") + 500);' B- M7 \8 A7 N$ m) z
7 D: b9 {4 ]0 G& n: T! s' O: J
    result = result.Substring(0, result.IndexOf("</div"));
/ k4 }3 _! g8 ^% u. w* g2 ?
, S3 q2 c: T# G4 U( @0 ^6 O
" S2 w# N0 c% l6 l: D' |% W

& n/ l9 b; G3 e% x    return result;8 @+ ?/ p% [1 a7 J2 b
! u! D' R2 p8 n8 w0 V6 K! |6 ~
}- \' {% D- Q) V+ J- s9 G5 `. G+ K
More details about this Unofficial Google Translation API can be found Here




欢迎光临 冒险解谜游戏中文网 ChinaAVG (https://chinaavg.com/) Powered by Discuz! X3.2