我想用印度语翻译文字。我已经阅读了很多文章但却无法理解如何这样做。我也看过谷歌翻译的一些文章,但没有提供在代码中使用它的指南。 请指导我如何才能这样做。我是否需要在应用程序中为所有语言添加字体?
我已粘贴以下代码,现在收到错误。无法理解那是什么错误。 错误是“索引和长度必须引用字符串中的位置。 参数名称:长度“。
以下是我的代码。
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”。
答案 0 :(得分:5)
为什么不尝试这些?
google-language-api-for-dotnet
http://code.google.com/p/google-language-api-for-dotnet/
使用Google翻译
翻译C#中的文字http://dnknormark.net/post/Translate-text-in-C-using-Google-Translate.aspx
Google翻译
http://www.codeproject.com/KB/IP/GoogleTranslator.aspx
使用Google Api翻译文字
http://blogs.msdn.com/shahpiyush/archive/2007/06/09/3188246.aspx
从C#调用Google Ajax语言API进行翻译和语言检测
C#中的翻译Web服务
http://www.codeproject.com/KB/cpp/translation.aspx
使用.NET的Google翻译API
答案 1 :(得分:0)
应用程序需要带有单词和键的XML文件。我创建了一个“全球化”文件夹,用于输入带有字典列表的XML文件
XML文件结构如下
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 } };
}
}