在asp.net C#web应用程序中翻译其他语言的文本

时间:2012-03-29 06:34:29

标签: asp.net web-services c#-4.0 google-api

我想用印度语翻译文字。我已经阅读了很多文章但却无法理解如何这样做。我也看过谷歌翻译的一些文章,但没有提供在代码中使用它的指南。 请指导我如何才能这样做。我是否需要在应用程序中为所有语言添加字体?

我已粘贴以下代码,现在收到错误。无法理解那是什么错误。 错误是“索引和长度必须引用字符串中的位置。 参数名称:长度“。

以下是我的代码。

 public string TranslateText(string input, string languagePair)
 {
    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("id=result_box") + 22, result.IndexOf("id=result_box") + 500);
    result = result.Substring(0, result.IndexOf("</div"));
    return result;
}
protected void btnTranslate_Click(object sender, EventArgs e)
{
    string convertTo="en|"+ddlLanguages.SelectedValue;
    txtTarget.Text = TranslateText(txtLanguage.Text, convertTo);
}

两个文本框的ID是源语言的“txtLanguage”和目标语言的“txtTarget”。

2 个答案:

答案 0 :(得分:5)

答案 1 :(得分:0)

应用程序需要带有单词和键的XML文件。我创建了一个“全球化”文件夹,用于输入带有字典列表的XML文件

enter image description here

XML文件结构如下

enter image description here

enter image description here

enter image description here 类翻译配置

using System.IO;
using System.Threading;
public class TranslateConfigurations
{
    public string Extension { get; set; } = ".xml";
    public string Culture { get { return Thread.CurrentThread.CurrentUICulture.Name; } }
    public string Path { get; set; } = @$"{Directory.GetCurrentDirectory().Split("bin")[0]}\Globalization\";
}

这是一种在应用程序路径中转换XML词典中的字符串的方法。

using domain.translate.Configurations;
using domain.translate.Contracts.Business;
using domain.translate.Utilities;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml.Linq;

public class TranslateBusiness : ITranslateBusiness
{
    private readonly ILogger<string> _logger;
    private readonly TranslateConfigurations _translateConfiguration;

    /// <summary>
    ///     
    /// </summary>
    /// <param name="logger"></param>
    public TranslateBusiness(ILogger<string> logger)
    {
        _logger = logger;
        _translateConfiguration = new TranslateConfigurations();
    }

    /// <summary>
    ///     Translate string with string culture
    /// </summary>
    /// <param name="wordKey"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    public object Translate(string wordKey, string strCulture)
    {
        try
        {
            var culture = !string.IsNullOrEmpty(strCulture) ? new CultureInfo(strCulture) : throw new CultureNotFoundException();

            return Messages.GenerateGenericSuccessObjectMessage("Translate", GetXmlSection(wordKey, culture.Name), 200);
        }
        catch (FileNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe o arquivo de tradução '{strCulture}'.", 404, wordKey);
        }
        catch (CultureNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe a cultura '{strCulture}'.", 404, wordKey);
        }
        catch (KeyNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe a chave '{wordKey}' no arquivo de tradução.", 404, wordKey);
        }
        catch (DirectoryNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe o caminho do arquivo de tradução.", 404, wordKey);
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return (e.Message != null && e?.InnerException?.Message != null) ? Messages.GenerateGenericErrorMessage(e.Message, e.InnerException.Message) : Messages.GenerateGenericErrorMessage(e.Message ?? e.InnerException.Message);
        }
    }

    /// <summary>
    ///     Translate string list with string culture
    /// </summary>
    /// <param name="wordKeys"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    public object Translate(List<string> wordKeys, string strCulture)
    {
        try
        {
            var culture = !string.IsNullOrEmpty(strCulture) ? new CultureInfo(strCulture) : throw new CultureNotFoundException();

            return Messages.GenerateGenericSuccessObjectMessage("Translate", GetXmlSection(wordKeys, culture.Name), 200);
        }
        catch (FileNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe o arquivo de tradução '{strCulture}'.", 404);
        }
        catch (CultureNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe a cultura '{strCulture}'.", 404, wordKeys);
        }
        catch (KeyNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existem as chaves no arquivo de tradução.", 404, wordKeys);
        }
        catch (DirectoryNotFoundException e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return Messages.GenerateGenericErrorMessage($"Não existe o caminho do arquivo de tradução.", 404);
        }
        catch (Exception e)
        {
            _logger.LogError(e.Message ?? e.InnerException.Message, null);
            return (e.Message != null && e?.InnerException?.Message != null) ? Messages.GenerateGenericErrorMessage(e.Message, e.InnerException.Message) : Messages.GenerateGenericErrorMessage(e.Message ?? e.InnerException.Message);
        }
    }

    #region Private methods

    /// <summary>
    ///     Get 
    /// </summary>
    /// <param name="key"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    private string GetXmlSection(string key, string culture = null)
    {
        XDocument doc = XDocument.Load($"{_translateConfiguration.Path}{culture ??_translateConfiguration.Culture}{_translateConfiguration.Extension}");
        var section = doc.Descendants().ToList().Where(n => n.FirstAttribute.Value == key);
        return section.FirstOrDefault()?.Value ?? throw new KeyNotFoundException();
    }

    /// <summary>
    ///     
    /// </summary>
    /// <param name="keys"></param>
    /// <param name="culture"></param>
    /// <returns></returns>
    private Dictionary<string, string> GetXmlSection(List<string> keys, string culture = null)
    {
        var dictionary = new Dictionary<string, string>();

        XDocument doc = XDocument.Load($"{_translateConfiguration.Path}{culture ?? _translateConfiguration.Culture}{_translateConfiguration.Extension}");

        foreach (var key in keys)
        {
            var section = doc.Descendants().ToList().Where(n => n.FirstAttribute.Value == key);
            dictionary.Add(key, section.FirstOrDefault().Value);
        }

        return dictionary.Count > 0 ? dictionary : throw new KeyNotFoundException();
    }

    #endregion Private methods
}

消息类

public static class Messages
{
    public static object GenerateGenericSuccessObjectMessage(string propertyName, object objectResult, int statusCode)
    {
        var property = new ExpandoObject() as IDictionary<string, object>;
        property.Add("Code", statusCode);
        property.Add(propertyName, objectResult);

        return property;
    }

    public static object GenerateGenericErrorMessage(string message, int statusCode, object objectResult)
    {
        return new { Error = new { Code = statusCode, Translate = objectResult, Message = message } };
    }

    public static object GenerateGenericErrorMessage(string message, int statusCode)
    {
        return new { Error = new { Code = statusCode, Message = message } };
    }

    public static object GenerateGenericErrorMessage(string message)
    {
        return new { Error = new { Code = 400, Message = message } };
    }

}