【问题标题】:Converting strings in c# from google translate从谷歌翻译转换c#中的字符串
【发布时间】:2015-02-25 03:42:54
【问题描述】:

我正在创建一个小字典,并带有使用谷歌翻译的附加选项。所以这就是问题所在:当我收到 Google 的回复并将其显示在文本框中时,我看到了某种奇怪的符号。 这是“询问”谷歌的方法的代码:

public string TranslateText(string inputText, string languagePair)
    {
        string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", inputText, languagePair);

        WebClient webClient = new WebClient();
        webClient.Encoding = System.Text.Encoding.UTF8;

        // Get translated text
        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>"));

        return result.Trim();
    }

..并像这样调用这个方法(点击翻译按钮后):

string resultText;
string inputText = tbInputWord.Text.ToString();

if (inputText != null && inputText.Trim() != "")
{
     ExtendedGoogleTranslate urlTranslate = new ExtendedGoogleTranslate();

     resultText = urlTranslate.TranslateText(inputText, "en|bg");

     tbOutputWord.Text = resultText;
 }

所以我正在从英语(en)翻译成保加利亚语(bg)并使用 UTF8 编码 webClient 所以我认为我在 调用者代码上遗漏了一些东西 以某种方式解析 resultText,然后将其放入 tbOutputWord 文本框。我知道这段代码有效,因为如果我选择从英语翻译成法语(例如),它会显示正确的结果。

【问题讨论】:

  • 你能提供一个http://www.google.com/translate_t?hl=en&amp;ie=UTF8&amp;text={0}&amp;langpair={1} 的示例请求,它会产生那些“奇怪的符号”吗?
  • 如果 inputText 等于 "hello" 结果应该是 "Здравейте" 而我看到的是 " ?????????" 但是如果我将 "en|bg" 更改为 "en|fr" 并使用相同的输入结果是“你好”

标签: c# string utf-8 google-translate


【解决方案1】:

不知何故,Google 不尊重 ie=UTF8 查询参数。我们需要在请求中添加一些标头,以便返回 UTF8:

WebClient webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
webClient.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0");
webClient.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8");

【讨论】:

  • 奇怪,但它有效!现在又出现了一个错误。当翻译这样的东西时:“嘿,你还好吗?”一切正常,但如果你这样写输入:“嘿!你还好吗?”它只翻译“嘿!”。此外,正如您在我的代码中看到的那样,我直接从 inputTextBox 读取(暂时),并且没有格式化,但看起来它一次只翻译一个句子。
  • 您应该 1.) 以不同的方式构造您的查询字符串。考虑这样做:stackoverflow.com/a/1877016/4317569 不过,您当前的问题是另一个问题:您需要 2.) 用于解析结果的正则表达式。在DownloadString 之后设置一个断点,你会看到你的翻译工作正常。你的解析是问题。
  • 用循环修复它,因为我看到响应包含每个句子的 标记。
  • 希望我有更多的 + 票给这个。在许多其他“解决方案”失败的情况下取得成功。
猜你喜欢
  • 2020-10-02
  • 1970-01-01
  • 2012-09-14
  • 1970-01-01
  • 2019-06-06
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多