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

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

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

采用Microsoft Visual Studio 2008设计,需要3.5运行库。
发布google在线翻译程序(附源码)

资源类:
/* •————————————————————————————————•
   | 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 ,如需转载请自行联系原作者

上一篇:oracle 19c RAC部署ADG手顺


下一篇:MySQL 优化:MySQL Where 执行顺序