当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net Google的translate工具翻译 API

asp.net Google的translate工具翻译 API

2018年04月19日  | 移动技术网IT编程  | 我要评论
在这篇,我就利用c#写一个小程序,翻译: 思路是这样的: 1:发送post(或者get) 2:获取post(或者get)的响应 3:正则匹配我们想要的值。 发生post(或
在这篇,我就利用c#写一个小程序,翻译:
思路是这样的:
1:发送post(或者get)
2:获取post(或者get)的响应
3:正则匹配我们想要的值。
发生post(或者get)的函数:
复制代码 代码如下:

public static string getgetrequest(string urlp,string encode){
if(null==urlp) return null;
string strretp = null;
stream datastream = null;
try{
httpwebrequest myhttpwebrequest=(httpwebrequest)webrequest.create(urlp);
myhttpwebrequest.timeout = 10000; // 10 secs
httpwebresponse objresponse =(httpwebresponse)myhttpwebrequest.getresponse();
//encoding enc = encoding.getencoding(1252); // windows default code page
if(objresponse.statusdescription == "ok"){//httpstatuscode.ok
datastream = objresponse.getresponsestream ();
encoding obje = string.isnullorempty(encode)?encoding.getencoding(0):encoding.getencoding(encode);
streamreader r = new streamreader(datastream,obje);
strretp= r.readtoend();
}
}catch(exception e){
strretp =e.message;
}finally{
if(null!=datastream) datastream.close();
}
return strretp;
}

这个我在前面的一些文章中有所介绍。
然后正则匹配的函数:
复制代码 代码如下:

public static string getmatchstring(string text,string pattern,int point){
if(string.isnullorempty(text)||string.isnullorempty(pattern))return string.empty;
regex rx = new regex(pattern,regexoptions.compiled | regexoptions.ignorecase | regexoptions.multiline);
match match = rx.match(text);
string word="";
if (match.success) word = match.groups[point].value;
return word.trim();
}

这个数根据一个正则表达数,返回匹配的值。
直接进入main主体:
复制代码 代码如下:

public static void main(string[] args){
string mess ="我们";
console.writeline(httputility.urlencode("我们"));
mess = getgetrequest("http://translate.google.com/translate_t?langpair="+httputility.urlencode("zh-cn|en")+ "&text="+httputility.urlencode(mess,system.text.unicodeencoding.getencoding( "gb2312")),"utf-8");
//console.writeline(mess);
mess = getmatchstring(mess,@"(<div id=result_box dir=""ltr"">)([?:\s\s]*?)(</div>)",2);
console.writeline(mess);
}

注意的是
httputility.urlencode(mess,system.text.unicodeencoding.getencoding( "gb2312"))
这句,无法识别urlencode的字符编码,这里需要指明。
ok,然后csc了,编译一下,下载一下吧。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网