以下是我使用谷歌翻译的代码。我添加了一个 dll 作为参考:Google.Apis.Translate.V2
我还购买了 Google Translate API 密钥。
我有 5 个错误,因为我不知道我需要更多的 dll:这些对象不存在缺少命名空间:DataContractJsonSerializer、TranslationRootObject、TranslationRootObject
这些命名空间需要什么 dll 引用?
这是我的代码,没有我的 API 密钥:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
namespace Google_Translate
{
public partial class Form1 : Form
{
static string apiKey = "";
static string texttotranslate = "hello world";
string text;
static String apiUrl = "https://www.googleapis.com/language/translate/v2?key={0}&source={1}&target={2}&q={3}";
static String url = String.Format(apiUrl, apiKey, "en", "ge", texttotranslate);
Stream outputStream = null;
byte[] bytes = Encoding.ASCII.GetBytes(url);
// create the http web request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
public Form1()
{
InitializeComponent();
webRequest.KeepAlive = true;
webRequest.Method = "POST";
// Overrride the GET method as documented on Google's docu.
webRequest.Headers.Add("X-HTTP-Method-Override: GET");
webRequest.ContentType = "application/x-www-form-urlencoded";
// send POST
try
{
webRequest.ContentLength = bytes.Length;
outputStream = webRequest.GetRequestStream();
outputStream.Write(bytes, 0, bytes.Length);
outputStream.Close();
}
catch (HttpListenerException e)
{
/*...*/
}
translate();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private string translate()
{
try
{
// get the response
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK && webRequest != null)
{
// read response stream
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string lista = sr.ReadToEnd();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TranslationRootObject));
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(lista));
TranslationRootObject tRootObject = (TranslationRootObject)serializer.ReadObject(stream);
string previousTranslation = string.Empty;
//deserialize
for (int i = 0; i < tRootObject.Data.Detections.Count; i++)
{
string translatedText = tRootObject.Data.Detections[i].TranslatedText.ToString();
if (i == 0)
{
text = translatedText;
}
else
{
if (!text.Contains(translatedText))
{
text = text + " " + translatedText;
}
}
}
return text;
}
}
}
catch (HttpListenerException e)
{
/*...*/
}
return text;
}
}
}
有人可以修复我的代码或告诉我有什么问题吗?
我需要的是翻译 29-33kb 的文本文件大小,我想知道在使用谷歌翻译网站时是否可以像在线翻译一样快。
我还发现这个链接Google Translate V2 cannot hanlde large text translations from C#有人说翻译不能翻译大文件,所以我想知道 29-33kb 的文件是否算大?如果是这样,也许有人可以查看链接并根据链接中的答案修复我的代码,我现在尝试了很多但并没有真正理解它。但首先我需要找出为什么我的原始代码在这里不起作用。