天天看点

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

需要的朋友可以下载,这几天看到园子里有几个兄弟编写Google的在线翻译;

我也凑一下热闹,网络收集了些资源,自己重新加工了一下,希望能对园子里的朋友有用。

功能:支持简体中文、法语、德语、意大利语、西班牙玉,葡萄牙语;

大家可以根据自己的需要扩充。

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

资源类:

/* •————————————————————————————————•

   | Email:[email protected] |

   | 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

        /// Gets and sets the user agent string.

        public string Agent

            get

            { return m_strAgent; }

            set

            { m_strAgent = (value == null ? "" : value); }

        /// Gets and sets the referer string.

        public string Referer

            { return m_strReferer; }

            { m_strReferer = (value == null ? "" : value); }

        /// Gets and sets the minimum pause time interval (in mSec).

        public int Pause

            { return m_nPause; }

            { m_nPause = value; }

        /// Gets and sets the timeout (in mSec).

        public int Timeout

            { return m_nTimeout; }

            { m_nTimeout = value; }

        /// Returns the retrieved content.

        /// <value>The content.</value>

        public string Content

            { return m_strContent; }

        /// Gets the fetch timestamp.

        public DateTime FetchTime

            { return m_tmFetchTime; }

        /// Gets the last error message, if any.

        public string ErrorMsg

            { return m_strError; }

        // Operations

        /// Resets the state of the object.

        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;

        /// Fetches the web resource.

        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

        /// Provides the derived class with an opportunity to initialize itself.

        /// <returns>true if the operation succeeded, false otherwise.</returns>

        protected virtual bool init()

        { return true; }

        /// Returns the url to be fetched.

        /// <returns>The url to be fetched.</returns>

        abstract protected string getFetchUrl();

        /// 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 "arg=val [&arg=val]...".

        /// <returns>A string containing the POST data or null if none.</returns>

        protected virtual string getPostData()

        { return null; }

        /// Provides the derived class with an opportunity to parse the fetched content.

        protected virtual void parseContent()

        { }

        /// Informs the framework that it needs to continue fetching urls.

        /// <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)

        /// Retrieves the content of the url to be fetched.

        /// <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

            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;

            finally

                if (resp != null)

                    m_httpStatusCode = resp.StatusCode;

            // Store retrieved content

                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();

            // 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...";

            gt = new GoogleTranslator(reverseMode);

            string strReverseTranslation = gt.translate(strTranslation);

            editReverseTranslation.Text = strReverseTranslation;

            lblStatus.Text = "";

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

继续阅读