发布google在线翻译程序(附源码)

简介:
需要的朋友可以下载,这几天看到园子里有几个兄弟编写Google的在线翻译;
我也凑一下热闹,网络收集了些资源,自己重新加工了一下,希望能对园子里的朋友有用。

功能:支持简体中文、法语、德语、意大利语、西班牙玉,葡萄牙语;
大家可以根据自己的需要扩充。

采用 Microsoft Visual Studio 2008设计,需要3.5运行库。


资源类:
/* •————————————————————————————————•
   | Email:gordon.gao@achievo.com |
   | amend:Gordon(高阳)                 |
   | 2008.4.14                    |
   •————————————————————————————————• */
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
namespace RavSoft
{
    /// <summary>
    /// A framework to expose information rendered by a URL (i.e. a "web
    /// resource") as an object that can be manipulated by an application.
    /// You use WebResourceProvider by deriving from it and implementing
    /// getFetchUrl() and optionally overriding other methods.
    /// </summary>
    abstract public class WebResourceProvider
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public WebResourceProvider()
        {
            reset();
        }
        /////////////
        // Properties
        /// <summary>
        /// Gets and sets the user agent string.
        /// </summary>
        public string Agent
        {
            get
            { return m_strAgent; }
            set
            { m_strAgent = (value == null ? "" : value); }
        }
        /// <summary>
        /// Gets and sets the referer string.
        /// </summary>
        public string Referer
        {
            get
            { return m_strReferer; }
            set
            { m_strReferer = (value == null ? "" : value); }
        }
        /// <summary>
        /// Gets and sets the minimum pause time interval (in mSec).
        /// </summary>
        public int Pause
        {
            get
            { return m_nPause; }
            set
            { m_nPause = value; }
        }
        /// <summary>
        /// Gets and sets the timeout (in mSec).
        /// </summary>
        public int Timeout
        {
            get
            { return m_nTimeout; }
            set
            { m_nTimeout = value; }
        }
        /// <summary>
        /// Returns the retrieved content.
        /// </summary>
        /// <value>The content.</value>
        public string Content
        {
            get
            { return m_strContent; }
        }
        /// <summary>
        /// Gets the fetch timestamp.
        /// </summary>
        public DateTime FetchTime
        {
            get
            { return m_tmFetchTime; }
        }
        /// <summary>
        /// Gets the last error message, if any.
        /// </summary>
        public string ErrorMsg
        {
            get
            { return m_strError; }
        }
        /////////////
        // Operations
        /// <summary>
        /// Resets the state of the object.
        /// </summary>
        public void reset()
        {
            m_strAgent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)";
            m_strReferer = "";
            m_strError = "";
            m_strContent = "";
            m_httpStatusCode = HttpStatusCode.OK;
            m_nPause = 0;
            m_nTimeout = 0;
            m_tmFetchTime = DateTime.MinValue;
        }
        /// <summary>
        /// Fetches the web resource.
        /// </summary>
        public void fetchResource()
        {
            // Initialize the provider - quit if initialization fails
            if (!init())
                return;
            // Main loop
            bool bOK = false;
            do
            {
                string url = getFetchUrl();
                getContent(url);
                bOK = (m_httpStatusCode == HttpStatusCode.OK);
                if (bOK)
                    parseContent();
            }
            while (bOK && continueFetching());
        }
        //////////////////
        // Virtual methods
        /// <summary>
        /// Provides the derived class with an opportunity to initialize itself.
        /// </summary>
        /// <returns>true if the operation succeeded, false otherwise.</returns>
        protected virtual bool init()
        { return true; }
        /// <summary>
        /// Returns the url to be fetched.
        /// </summary>
        /// <returns>The url to be fetched.</returns>
        abstract protected string getFetchUrl();
        /// <summary>
        /// Retrieves the POST data (if any) to be sent to the url to be fetched.
        /// The data is returned as a string of the form &quot;arg=val [&amp;arg=val]...&quot;.
        /// </summary>
        /// <returns>A string containing the POST data or null if none.</returns>
        protected virtual string getPostData()
        { return null; }
        /// <summary>
        /// Provides the derived class with an opportunity to parse the fetched content.
        /// </summary>
        protected virtual void parseContent()
        { }
        /// <summary>
        /// Informs the framework that it needs to continue fetching urls.
        /// </summary>
        /// <returns>
        /// true if the framework needs to continue fetching urls, false otherwise.
        /// </returns>
        protected virtual bool continueFetching()
        { return false; }
        ///////////////////////////
        // Implementation (members)
        /// <summary>User agent string used when making an HTTP request.</summary>
        string m_strAgent;
        /// <summary>Referer string used when making an HTTP request.</summary>
        string m_strReferer;
        /// <summary>Error message.</summary>
        string m_strError;
        /// <summary>Retrieved.</summary>
        string m_strContent;
        /// <summary>HTTP status code.</summary>
        HttpStatusCode m_httpStatusCode;
        /// <summary>Minimum number of mSecs to pause between successive HTTP requests.</summary>
        int m_nPause;
        /// <summary>HTTP request timeout (in mSecs).</summary>
        int m_nTimeout;
        /// <summary>Timestamp of last fetch.</summary>
        DateTime m_tmFetchTime;
        ///////////////////////////
        // Implementation (methods)
        /// <summary>
        /// Retrieves the content of the url to be fetched.
        /// </summary>
        /// <param name="url">Url to be fetched.</param>
        void getContent
          (string url)
        {
            // Pause, if necessary
            if (m_nPause > 0)
            {
                int nElapsedMsec = 0;
                do
                {
                    // Determine the time elapsed since the last fetch (if any)
                    if (nElapsedMsec == 0)
                    {
                        if (m_tmFetchTime != DateTime.MinValue)
                        {
                            TimeSpan tsElapsed = m_tmFetchTime - DateTime.Now;
                            nElapsedMsec = (int)tsElapsed.TotalMilliseconds;
                        }
                    }
                    // Pause 100mSec increment if necessary
                    int nSleepMsec = 100;
                    if (nElapsedMsec < m_nPause)
                    {
                        Thread.Sleep(nSleepMsec);
                        nElapsedMsec += nSleepMsec;
                    }
                }
                while (nElapsedMsec < m_nPause);
            }
            // Set up the fetch request
            string strUrl = url;
            if (!strUrl.StartsWith("http://"))
                strUrl = "http://" + strUrl;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl);
            req.AllowAutoRedirect = true;
            req.UserAgent = m_strAgent;
            req.Referer = m_strReferer;
            if (m_nTimeout != 0)
                req.Timeout = m_nTimeout;
            // Add POST data (if present)
            string strPostData = getPostData();
            if (strPostData != null)
            {
                ASCIIEncoding asciiEncoding = new ASCIIEncoding();
                byte[] postData = asciiEncoding.GetBytes(strPostData);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = postData.Length;
                Stream reqStream = req.GetRequestStream();
                reqStream.Write(postData, 0, postData.Length);
                reqStream.Close();
            }
            // Fetch the url - return on error
            m_strError = "";
            m_strContent = "";
            HttpWebResponse resp = null;
            try
            {
                m_tmFetchTime = DateTime.Now;
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch (Exception exc)
            {
                if (exc is WebException)
                {
                    WebException webExc = exc as WebException;
                    m_strError = webExc.Message;
                }
                return;
            }
            finally
            {
                if (resp != null)
                    m_httpStatusCode = resp.StatusCode;
            }
            // Store retrieved content
            try
            {
                Stream stream = resp.GetResponseStream();
                StreamReader streamReader = new StreamReader(stream);
                m_strContent = streamReader.ReadToEnd();
            }
            catch (Exception)
            {
                // Read failure occured - nothing to do
            }
        }
    }
}

调用:

   private void OnTranslate(object sender, System.EventArgs e)
        {
            // Get English text - complain if none
            string strEnglish = editEnglish.Text.Trim();
            if (strEnglish.Equals(String.Empty))
            {
                MessageBox.Show("Please enter the text to be translated.",
                                 "GoogleTranslatorForm Demo",
                                 MessageBoxButtons.OK,
                                 MessageBoxIcon.Warning);
                editEnglish.SelectAll();
                editEnglish.Focus();
                return;
            }
            // Get translation mode
            GoogleTranslator.Mode mode = GoogleTranslator.Mode.EnglishToFrench;
            GoogleTranslator.Mode reverseMode = GoogleTranslator.Mode.FrenchToEnglish;
            if (radioGerman.Checked)
            {
                mode = GoogleTranslator.Mode.EnglishToGerman;
                reverseMode = GoogleTranslator.Mode.GermanToEnglish;
            }
            else
            {
                if (radioItalian.Checked)
                {
                    mode = GoogleTranslator.Mode.EnglishToItalian;
                    reverseMode = GoogleTranslator.Mode.ItalianToEnglish;
                }
                else
                {
                    if (radioSpanish.Checked)
                    {
                        mode = GoogleTranslator.Mode.EnglishToSpanish;
                        reverseMode = GoogleTranslator.Mode.SpanishToEnglish;
                    }
                    else
                    {
                        if (radioPortugese.Checked)
                        {
                            mode = GoogleTranslator.Mode.EnglishToPortugese;
                            reverseMode = GoogleTranslator.Mode.PortugeseToEnglish;
                        }
                        else
                        {
                            if (radioChina.Checked)
                            {
                                mode = GoogleTranslator.Mode.EnglishToChina;
                                reverseMode = GoogleTranslator.Mode.ChinaToEnlish;
                            }
                        }
                    }
                }
            }
            // Translate the text and update the display
            lblStatus.Text = "Translating...";
            lblStatus.Update();
            GoogleTranslator gt = new GoogleTranslator(mode);
            string strTranslation = gt.translate(strEnglish);
            editTranslation.Text = strTranslation;
            editTranslation.Update();
            lblStatus.Text = "Reverse translating...";
            lblStatus.Update();
            gt = new GoogleTranslator(reverseMode);
            string strReverseTranslation = gt.translate(strTranslation);
            editReverseTranslation.Text = strReverseTranslation;
            lblStatus.Text = "";
        }

详细的我就不说了,自己开源码吧。

 

本文转自  高阳 51CTO博客,原文链接:http://blog.51cto.com/xiaoyinnet/196089 ,如需转载请自行联系原作者

目录
打赏
0
0
0
0
95
分享
相关文章
|
8月前
|
在 HTML 中禁用 Chrome 浏览器的 Google 翻译功能
在 html 标签中添加 translate=“no” 属性,浏览器将不会翻译整个页面。
373 0
vue3-ts-vite:Google 多语言调试 / 网页中插入谷歌翻译元素 / 翻译
vue3-ts-vite:Google 多语言调试 / 网页中插入谷歌翻译元素 / 翻译
333 0
Linux 提权-SUID/SGID_1 本文通过 Google 翻译 SUID | SGID Part-1 – Linux Privilege Escalation 这篇文章所产生,本人仅是对机器翻译中部分表达别扭的字词进行了校正及个别注释补充。
接下来,让我们看看 SUID3NUM 在枚举 SUID 二进制文件方面的表现如何。 3.2、枚举 SUID 二进制文件 – SUID3NUM 我们将用来枚举 SUID 二进制文件的第二个工具是 SUID3NUM。这是一个很棒的工具,因为它是专门为枚举 SUID 二进制文件而创建的。但这还不是全部,它还提供了可用于提升权限的命令(命令从 GTFOBins 中提取)。 这还不是最好的部分,SUID3NUM 还具有内置的 autopwn 功能,可以通过 -e 开关激活! 在 OSCP 考试中也使用此工具,只要您不使用自动利用功能。 3.2.1、下载并执行 SUID3NUM 我们可以从 GitHubs
55 0
【sgGoogleTranslate】自定义组件:基于Vue.js用谷歌Google Translate翻译插件实现网站多国语言开发
【sgGoogleTranslate】自定义组件:基于Vue.js用谷歌Google Translate翻译插件实现网站多国语言开发
完美修复google翻译失效的问题
使用chrome的小伙伴应该都知道有个页面一键翻译,对于英语相当蹩脚的我来说灰常好用,然而…
199 0
Google Earth Engine——美国PRISM插值程序模拟了天气和气候如何随海拔变化,并考虑了海岸效应、温度反转和可能导致雨影的地形障碍。
Google Earth Engine——美国PRISM插值程序模拟了天气和气候如何随海拔变化,并考虑了海岸效应、温度反转和可能导致雨影的地形障碍。
186 0
Google Earth Engine——美国PRISM插值程序模拟了天气和气候如何随海拔变化,并考虑了海岸效应、温度反转和可能导致雨影的地形障碍。
Google Java编程风格规范(2020年4月原版翻译)
Google Java Style Guide 这份文档是Google Java编程风格规范的完整定义。当且仅当一个Java源文件符合此文档中的规则, 我们才认为它符合Google的Java编程风格。 与其它的编程风格指南一样,这里所讨论的不仅仅是编码格式美不美观的问题, 同时也讨论一些约定及编码标准。然而,这份文档主要侧重于我们所普遍遵循的规则,
1184 0

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等