1using System; 2using System.Collections.Generic; 3 4using System.Text; 5using System.Net; 6using System.IO; 7using Newtonsoft.Json; 8using System.Web; 9using System.Text.RegularExpressions; 10 11namespace Framework 12{ 13 /// <summary> 14 /// 语言类型 15 /// </summary> 16 public class LanguageType 17 { 18 /// <summary> 19 /// 中文 20 /// </summary> 21 public static string Chinese = "zh-cn"; 22 /// <summary> 23 /// 英文 24 /// </summary> 25 public static string English = "en"; 26 } 27 /// <summary> 28 /// 翻译方式类型 29 /// </summary> 30 public class TranslationType 31 { 32 /// <summary> 33 /// Google 34 /// </summary> 35 public static string Google = "GoogleTanslater"; 36 /// <summary> 37 /// Bing 38 /// </summary> 39 public static string Bing = "MircsoftTanslater"; 40 } 41 /// <summary> 42 /// 语言翻译类 43 /// </summary> 44 public class Translater 45 { 46 /// <summary> 47 /// 翻译方法 中文:"zh-cn", 英文:"en" type:MircsoftTanslater,GoogleTanslater 48 /// </summary> 49 /// <param name="sourceText">翻译原文</param> 50 /// <param name="fromLanguage">原始语言</param> 51 /// <param name="toLanguage">目标语言</param> 52 /// <param name="type">翻译API</param> 53 /// <returns>译文</returns> 54 public static string Translate(string sourceText, string fromLanguage, string toLanguage, string type = "MircsoftTanslater") 55 { 56 string translateStr = string.Empty; 57 switch (type) 58 { 59 case "MircsoftTanslater": 60 translateStr = MircsoftTanslater(sourceText, fromLanguage, toLanguage);//"zh-cn", "en"; 61 break; 62 case "GoogleTanslater": 63 translateStr = GoogleTranslater_PostMethod(sourceText, fromLanguage, toLanguage);//"zh-cn", "en"; 64 break; 65 } 66 return translateStr; 67 } 68 #region Google 翻译: Get方式获取翻译 69 /// <summary> 70 /// Google 翻译: Get方式获取翻译 71 /// </summary> 72 /// <param name="sourceText"></param> 73 /// <param name="fromType"></param> 74 /// <param name="toType"></param> 75 /// <returns></returns> 76 private static string GoogleTranslater_GetMethod(string sourceText, string fromType, string toType) 77 { 78 string result; 79 string langPair = fromType.ToLower() == "zh-cn" ? "zh|en" : "en|zh"; 80 string url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=" + HttpUtility.UrlEncode(langPair) + "&q=" + HttpUtility.UrlEncode(sourceText); 81 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 82 request.Method = "GET"; 83 request.Referer = "http://www.my-ajax-site.com"; 84 try 85 { 86 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 87 Stream responseStream = response.GetResponseStream(); 88 StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8")); 89 string responseStr = reader.ReadToEnd(); 90 ResponseResult readConfig = (ResponseResult)JavaScriptConvert.DeserializeObject(responseStr, typeof(ResponseResult)); 91 if (readConfig.responseStatus == "200") 92 { 93 result = readConfig.responseData.translatedText; 94 } 95 else 96 { 97 result = readConfig.responseStatus; 98 } 99 } 100 catch (Exception Ex) 101 { 102 result = "err:" + Ex.Message; 103 } 104 return result; 105 } 106 #endregion 107 #region Google 翻译: Post方式获取翻译 108 /// <summary> 109 /// Google 翻译: Post方式获取翻译 110 /// </summary> 111 /// <param name="sourceText"></param> 112 /// <param name="fromType"></param> 113 /// <param name="toType"></param> 114 /// <returns></returns> 115 private static string GoogleTranslater_PostMethod(string sourceText, string fromType, string toType) 116 { 117 string fromLan = fromType.ToLower() == "zh-cn" ? "zh" : "en"; 118 string toLan = toType.ToLower() == "zh-cn" ? "zh" : "en"; 119 HttpWebRequest requestScore = (HttpWebRequest)WebRequest.Create("http://translate.google.com/translate_t#"); 120 StringBuilder postContent = new StringBuilder(); 121 Encoding myEncoding = Encoding.UTF8; 122 postContent.Append(HttpUtility.UrlEncode("hl", myEncoding)); 123 postContent.Append("="); 124 postContent.Append(HttpUtility.UrlEncode("en", myEncoding)); 125 postContent.Append("&"); 126 postContent.Append(HttpUtility.UrlEncode("ie", myEncoding)); 127 postContent.Append("="); 128 postContent.Append(HttpUtility.UrlEncode("UTF-8", myEncoding)); 129 postContent.Append("&"); 130 postContent.Append(HttpUtility.UrlEncode("sl", myEncoding)); 131 postContent.Append("="); 132 postContent.Append(HttpUtility.UrlEncode(fromLan, myEncoding)); 133 postContent.Append("&"); 134 postContent.Append(HttpUtility.UrlEncode("text", myEncoding)); 135 postContent.Append("="); 136 postContent.Append(HttpUtility.UrlEncode(sourceText, myEncoding)); 137 postContent.Append("&"); 138 postContent.Append(HttpUtility.UrlEncode("tl", myEncoding)); 139 postContent.Append("="); 140 postContent.Append(HttpUtility.UrlEncode(toLan, myEncoding)); 141 142 byte[] data = Encoding.ASCII.GetBytes(postContent.ToString()); 143 requestScore.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; 144 requestScore.Method = "Post"; 145 //requestScore.ContentType = "application/x-www-form-urlencoded;charset=gb2312"; 146 requestScore.ContentLength = data.Length; 147 requestScore.KeepAlive = true; 148 requestScore.Timeout = (6 * 60 * 1000); 149 requestScore.ProtocolVersion = HttpVersion.Version10; 150 151 Stream stream = requestScore.GetRequestStream(); 152 stream.Write(data, 0, data.Length); 153 stream.Close(); 154 string content = string.Empty; 155 try 156 { 157 System.Net.ServicePointManager.Expect100Continue = false; 158 HttpWebResponse responseSorce = (HttpWebResponse)requestScore.GetResponse(); 159 StreamReader reader = new StreamReader(responseSorce.GetResponseStream()); 160 content = reader.ReadToEnd(); 161 responseSorce.Close(); 162 reader.Dispose(); 163 stream.Dispose(); 164 } 165 catch (WebException ex) 166 { 167 HttpWebResponse responseSorce = (HttpWebResponse)ex.Response;//得到请求网站的详细错误提示 168 StreamReader reader = new StreamReader(responseSorce.GetResponseStream()); 169 content = reader.ReadToEnd(); 170 responseSorce.Close(); 171 reader.Dispose(); 172 stream.Dispose(); 173 } 174 finally 175 { 176 requestScore.Abort(); 177 } 178 string reg = @"<(?<HtmlTag>[\w]+)[^>]*\s[iI][dD]=(?<Quote>[""']?)result_box(?(Quote)\k<Quote>)[""']?[^>]*>((?<Nested><\k<HtmlTag>[^>]*>)|</\k<HtmlTag>>(?<-Nested>)|.*?)*</\k<HtmlTag>>"; 179 //string reg = @"<(span) id=result_box [^>]*>.*?</\1>";//匹配出翻译内容 180 Regex r = new Regex(reg); 181 MatchCollection mcItem = r.Matches(content); 182 string result = ConvertHtmlToText(mcItem[0].Value); 183 return result; 184 } 185 /// <summary> 186 /// 将HTML转换为纯文本 187 /// </summary> 188 /// <param name="source"></param> 189 /// <returns></returns> 190 public static string ConvertHtmlToText(string source) 191 { 192 // 代码的实现的思路是: 193 //a、先将html文本中的所有空格、换行符去掉(因为html中的空格和换行是被忽略的) 194 //b、将<head>标记中的所有内容去掉 195 //c、将<script>标记中的所有内容去掉 196 //d、将<style>标记中的所有内容去掉 197 //e、将td换成空格,tr,li,br,p 等标记换成换行符 198 //f、去掉所有以“<>”符号为头尾的标记去掉。 199 //g、转换&,&nbps;等转义字符换成相应的符号 200 //h、去掉多余的空格和空行 201 string result; 202 //remove line breaks,tabs 203 result = source.Replace("\r", " "); 204 result = result.Replace("\n", " "); 205 result = result.Replace("\t", " "); 206 //remove the header 207 result = Regex.Replace(result, "(<head>).*(</head>)", string.Empty, RegexOptions.IgnoreCase); 208 result = Regex.Replace(result, @"<( )*script([^>])*>", "<script>", RegexOptions.IgnoreCase); 209 result = Regex.Replace(result, @"(<script>).*(</script>)", string.Empty, RegexOptions.IgnoreCase); 210 //remove all styles 211 result = Regex.Replace(result, @"<( )*style([^>])*>", "<style>", RegexOptions.IgnoreCase); //clearing attributes 212 result = Regex.Replace(result, "(<style>).*(</style>)", string.Empty, RegexOptions.IgnoreCase); 213 //insert tabs in spaces of <td> tags 214 result = Regex.Replace(result, @"<( )*td([^>])*>", " ", RegexOptions.IgnoreCase); 215 //insert line breaks in places of <br> and <li> tags 216 result = Regex.Replace(result, @"<( )*br( )*>", "\r", RegexOptions.IgnoreCase); 217 result = Regex.Replace(result, @"<( )*li( )*>", "\r", RegexOptions.IgnoreCase); 218 //insert line paragraphs in places of <tr> and <p> tags 219 result = Regex.Replace(result, @"<( )*tr([^>])*>", "\r\r", RegexOptions.IgnoreCase); 220 result = Regex.Replace(result, @"<( )*p([^>])*>", "\r\r", RegexOptions.IgnoreCase); 221 //remove anything thats enclosed inside < > 222 result = Regex.Replace(result, @"<[^>]*>", string.Empty, RegexOptions.IgnoreCase); 223 //replace special characters: 224 result = Regex.Replace(result, @"&", "&", RegexOptions.IgnoreCase); 225 result = Regex.Replace(result, @" ", " ", RegexOptions.IgnoreCase); 226 result = Regex.Replace(result, @"<", "<", RegexOptions.IgnoreCase); 227 result = Regex.Replace(result, @">", ">", RegexOptions.IgnoreCase); 228 result = Regex.Replace(result, @"&(.{2,6});", string.Empty, RegexOptions.IgnoreCase); 229 //remove extra line breaks and tabs 230 result = Regex.Replace(result, @" ( )+", " "); 231 result = Regex.Replace(result, "(\r)( )+(\r)", "\r\r"); 232 result = Regex.Replace(result, @"(\r\r)+", "\r\n"); 233 return result; 234 } 235 #endregion 236 #region 微软翻译 237 /// <summary> 238 /// 微软翻译API : 语言类型:"zh-cn", "en" 239 /// </summary> 240 /// <param name="orgStr">翻译原文</param> 241 /// <param name="fromType">原文语言类型</param> 242 /// <param name="toType">目标语言类型</param> 243 /// <returns></returns> 244 public static string MircsoftTanslater(string orgStr, string fromType, string toType) 245 { 246 string content = string.Empty; 247 string appId = "56E164FED4017D272E06AD7E16778536251CA5CB"; 248 string text = orgStr;// "Translate this for me"; 249 string from = fromType;// "en"; 250 string to = toType;// "zh-cn"; 251 252 string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=" + appId + "&text=" + System.Web.HttpUtility.UrlEncode(text) + "&from=" + from + "&to=" + to; 253 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri); 254 WebResponse response = null; 255 try 256 { 257 response = httpWebRequest.GetResponse(); 258 StreamReader reader = new StreamReader(response.GetResponseStream()); 259 content = reader.ReadToEnd();//"<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Hello, China</string>" 260 content = content.Replace("<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">", ""); 261 content = content.Replace("</string>", ""); 262 response.Close(); 263 reader.Dispose(); 264 } 265 catch (WebException e) 266 { 267 content = ProcessWebException(e, "Failed to translate"); 268 } 269 finally 270 { 271 if (response != null) 272 { 273 response.Close(); 274 response = null; 275 } 276 } 277 return content; 278 } 279 private static string ProcessWebException(WebException e, string message) 280 { 281 string result = string.Empty; 282 result = string.Format("{0}: {1}", message, e.ToString()); 283 // Obtain detailed error information 284 string strResponse = string.Empty; 285 using (HttpWebResponse response = (HttpWebResponse)e.Response) 286 { 287 using (Stream responseStream = response.GetResponseStream()) 288 { 289 using (StreamReader sr = new StreamReader(responseStream, System.Text.Encoding.ASCII)) 290 { 291 strResponse = sr.ReadToEnd(); 292 } 293 } 294 } 295 result = string.Format("Http status code={0}, error message={1}", e.Status, strResponse); 296 return result; 297 } 298 #endregion 299 } 300 /// <summary> 301 /// 翻译返回类 302 /// </summary> 303 public class ResponseResult 304 { 305 public ResponseData responseData { get; set; } 306 public string responseDetails { get; set; } 307 public string responseStatus { get; set; } 308 } 309 /// <summary> 310 /// 311 /// </summary> 312 public class ResponseData 313 { 314 public string translatedText { get; set; } 315 } 316}
Translater
Wesley13
2021-10-11
1009 0 0
点赞
收藏
评论区
加载中...