最近项目中有大量中译英的操作,搜集了一下大概还有2000多个汉语未翻译,
如果手工翻译费时费劲,于是程序员的懒惰激发了程序员的创造力,做了一个自动翻译接口,批量翻译只是一刹那的事情。
源码如下:
public
static
string
GoogleTranslate(
string
sourceWord,
string
fromLanguage,
string
toLanguage)
{
/*
调用: http://ajax.googleapis.com/ajax/services/language/translate?v=1.0 &langpair=zh-CN|en&q=中国人是好人
返回的json格式如下:
{"responseData": {"translatedText":"Chinese people are good people"}, "responseDetails": null, "responseStatus": 200} */
string serverUrl = @" http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair= "
+ fromLanguage + " | " + toLanguage + " &q= " + HttpUtility.UrlEncode(sourceWord);
WebRequest request = WebRequest.Create(serverUrl);
WebResponse response = request.GetResponse();
string resJson = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
int textIndex = resJson.IndexOf( " translatedText " ) + 17 ;
int textLen = resJson.IndexOf( " \" " ,textIndex) - textIndex;
return resJson.Substring(textIndex, textLen);
}
{
/*
调用: http://ajax.googleapis.com/ajax/services/language/translate?v=1.0 &langpair=zh-CN|en&q=中国人是好人
返回的json格式如下:
{"responseData": {"translatedText":"Chinese people are good people"}, "responseDetails": null, "responseStatus": 200} */
string serverUrl = @" http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair= "
+ fromLanguage + " | " + toLanguage + " &q= " + HttpUtility.UrlEncode(sourceWord);
WebRequest request = WebRequest.Create(serverUrl);
WebResponse response = request.GetResponse();
string resJson = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
int textIndex = resJson.IndexOf( " translatedText " ) + 17 ;
int textLen = resJson.IndexOf( " \" " ,textIndex) - textIndex;
return resJson.Substring(textIndex, textLen);
}
调用如下:
txtMsg.Text
=
GoogleTranslate(txtMsg.Text,
"
zh-CN
"
,
"
en
"
);
如有用得上的,请顶一下。