[关闭]
@ZSCDumin 2018-05-10T02:02:11.000000Z 字数 2151 阅读 649

谷歌翻译函数实现

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Security.Cryptography.X509Certificates;
  9. using System.Net.Security;
  10. using System.Text.RegularExpressions;
  11. namespace ConsoleApplication1
  12. {
  13. class Program
  14. {
  15. static void Main(string[] args)
  16. {
  17. string text = "Artificial intelligence is a branch of computer science.";
  18. string text1 = "Artificial [intelligence] is a branch of computer science.";
  19. string text2 = "Artificial intelligence is a branch of computer science Tom said.";
  20. Console.WriteLine(googleTranslation(text));
  21. Console.WriteLine(googleTranslation(text1));
  22. Console.WriteLine(googleTranslation(text2));
  23. }
  24. public static string googleTranslation(string text)
  25. {
  26. if (text == "" || text == null)
  27. {
  28. return "";
  29. }
  30. else
  31. {
  32. string result = "";
  33. string url = "https://translate.google.cn/translate_a/single?client=gtx&sl=en&tl=zh-CN&dt=t&q=" + text;
  34. string jsonData = GetInfo(url);
  35. string pattern = "\"([^\"]*)\"";
  36. int count = Regex.Matches(jsonData, pattern).Count;
  37. for (int i = 0; i < count - 1; i++)
  38. {
  39. Match match = Regex.Match(jsonData, pattern);
  40. result += match.Value.Trim().Replace("\"", "");
  41. }
  42. return result;
  43. }
  44. }
  45. public static string GetInfo(string url)
  46. {
  47. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  48. //访问http方法
  49. string strBuff = "";
  50. Uri httpURL = new Uri(url);
  51. ///HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法建立,并进行强制的类型转换
  52. HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
  53. ///通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换
  54. HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
  55. ///GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容
  56. ///若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理
  57. Stream respStream = httpResp.GetResponseStream();
  58. ///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以
  59. //StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8)
  60. StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
  61. strBuff = respStreamReader.ReadToEnd();
  62. return strBuff;
  63. }
  64. public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  65. {
  66. //直接确认,否则打不开
  67. return true;
  68. }
  69. }
  70. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注