从谷歌翻译获得一个奇怪的结果

时间:2014-03-15 13:12:35

标签: c# winforms google-translate

我一直在尝试翻译文本框内容,使用下面的代码,它在一行的字符串上运行得很好,但是当涉及到文本段落(包括换行符)时,它只是给了我这个结果: enter image description here 这是我正在使用的代码:

string input = textBox1.Text;
        string languagePair = "jp|en";

        string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
        WebClient webClient = new WebClient();
        webClient.Encoding = System.Text.Encoding.UTF8;
        string result = webClient.DownloadString(url);
        result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
        result = result.Substring(result.IndexOf(">") + 1);
        result = result.Substring(0, result.IndexOf("</span>"));
        result = WebUtility.HtmlDecode(result.Trim());
        MessageBox.Show(result);

以下是文字示例:http://pastebin.com/raw.php?i=e9Qcj7B6

1 个答案:

答案 0 :(得分:0)

我终于明白了,我必须修改代码并将其拆分以使其正常工作:

string input = textBox1.Text;
string languagePair = "jp|en";

string translation = "";
string[] lines = textBox1.Text.Split('\n');
if (lines.Length > 1)
{
    string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
    WebClient webClient = new WebClient();
    webClient.Encoding = Encoding.UTF8;
    string result = webClient.DownloadString(url);
    for (int i = 0; i < lines.Length; i++)
    {
        result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
        if (i != lines.Length - 1)
        {
            result = result.Substring(result.IndexOf(">") + 101);
        }
        else
        {
            result = result.Substring(result.IndexOf(">") + 1);
        }
        translation += result.Substring(0, result.IndexOf("</span>"));
    }
    //result = WebUtility.HtmlDecode(result.Trim()); <---- i didn't need this one since i translated from Japanese to English
    MessageBox.Show(translation.Replace("<br>", "\n"));
}
else
{
    string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
    WebClient webClient = new WebClient();
    webClient.Encoding = Encoding.UTF8;
    string result = webClient.DownloadString(url);
    result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
    result = result.Substring(result.IndexOf(">") + 1);
    result = result.Substring(0, result.IndexOf("</span>"));
    //result = WebUtility.HtmlDecode(result.Trim());
    MessageBox.Show(result.Replace("<br>", "\n"));
}