我們可以使用百度翻譯API獲取到翻譯結(jié)果
翻譯API地址:
http://api.fanyi.baidu.com/api/trans/vip/translate
?一、新建窗體應(yīng)用程序TranslatorDemo,將默認(rèn)的Form1重命名為FormTranslator。
窗體FormTranslator設(shè)計(jì)器如圖:
?窗體設(shè)計(jì)器源代碼如下:
文件:FormTranslator.Designer.cs
namespace TranslatorDemo
{
partial class FormTranslator
{
/// <summary>
/// 必需的設(shè)計(jì)器變量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的資源。
/// </summary>
/// <param name="disposing">如果應(yīng)釋放托管資源,為 true;否則為 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗體設(shè)計(jì)器生成的代碼
/// <summary>
/// 設(shè)計(jì)器支持所需的方法 - 不要修改
/// 使用代碼編輯器修改此方法的內(nèi)容。
/// </summary>
private void InitializeComponent()
{
this.bntToEnglish = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.rtxtChinese = new System.Windows.Forms.RichTextBox();
this.label2 = new System.Windows.Forms.Label();
this.rtxtEnglish = new System.Windows.Forms.RichTextBox();
this.btnToChinese = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// bntToEnglish
//
this.bntToEnglish.Location = new System.Drawing.Point(638, 181);
this.bntToEnglish.Name = "bntToEnglish";
this.bntToEnglish.Size = new System.Drawing.Size(102, 23);
this.bntToEnglish.TabIndex = 2;
this.bntToEnglish.Text = "中文轉(zhuǎn)英文>>";
this.bntToEnglish.UseVisualStyleBackColor = true;
this.bntToEnglish.Click += new System.EventHandler(this.bntToEnglish_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("宋體", 13F);
this.label1.Location = new System.Drawing.Point(9, 11);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(53, 18);
this.label1.TabIndex = 1;
this.label1.Text = "中文:";
//
// rtxtChinese
//
this.rtxtChinese.Location = new System.Drawing.Point(12, 44);
this.rtxtChinese.Name = "rtxtChinese";
this.rtxtChinese.Size = new System.Drawing.Size(609, 623);
this.rtxtChinese.TabIndex = 0;
this.rtxtChinese.Text = "";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("宋體", 13F);
this.label2.Location = new System.Drawing.Point(749, 11);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 18);
this.label2.TabIndex = 3;
this.label2.Text = "英文:";
//
// rtxtEnglish
//
this.rtxtEnglish.Location = new System.Drawing.Point(752, 44);
this.rtxtEnglish.Name = "rtxtEnglish";
this.rtxtEnglish.Size = new System.Drawing.Size(609, 624);
this.rtxtEnglish.TabIndex = 1;
this.rtxtEnglish.Text = "";
//
// btnToChinese
//
this.btnToChinese.Location = new System.Drawing.Point(638, 266);
this.btnToChinese.Name = "btnToChinese";
this.btnToChinese.Size = new System.Drawing.Size(102, 23);
this.btnToChinese.TabIndex = 3;
this.btnToChinese.Text = "<<英文轉(zhuǎn)中文";
this.btnToChinese.UseVisualStyleBackColor = true;
this.btnToChinese.Click += new System.EventHandler(this.btnToChinese_Click);
//
// FormTranslator
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1371, 679);
this.Controls.Add(this.btnToChinese);
this.Controls.Add(this.rtxtEnglish);
this.Controls.Add(this.label2);
this.Controls.Add(this.rtxtChinese);
this.Controls.Add(this.label1);
this.Controls.Add(this.bntToEnglish);
this.Name = "FormTranslator";
this.Text = "中文批量翻譯為英文";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button bntToEnglish;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.RichTextBox rtxtChinese;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.RichTextBox rtxtEnglish;
private System.Windows.Forms.Button btnToChinese;
}
}
二、新建關(guān)鍵翻譯類TranslateUtil
TranslateUtil.cs源程序如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Web.Security;
namespace TranslatorDemo
{
/// <summary>
/// 翻譯過程
/// </summary>
public class TranslateUtil
{
/// <summary>
/// 使用Get的方式調(diào)用百度API進(jìn)行翻譯
/// </summary>
/// <param name="content">要轉(zhuǎn)化的文本</param>
/// <param name="languageFrom">要轉(zhuǎn)化的語言</param>
/// <param name="languageTo">目標(biāo)語言</param>
/// <returns></returns>
public static FeedbackResult TranslateGet(string content, string languageFrom, string languageTo)
{
string appId = "20230722001753350";
string passWord = "your password";
string randomNum = new Random().Next().ToString();
string md5Sign = FormsAuthentication.HashPasswordForStoringInConfigFile(appId + content + randomNum + passWord, "MD5").ToLower();
string FullRequest = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" + content + "&from=" + languageFrom + "&to=" + languageTo + "&appid=" + appId + "&salt=" + randomNum + "&sign=" + md5Sign;
try
{
string resultContent = new WebClient().DownloadString(FullRequest);
FeedbackResult feedbackResult = new JavaScriptSerializer().Deserialize<FeedbackResult>(resultContent);
feedbackResult.ResponseJson = resultContent;
return feedbackResult;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return new FeedbackResult()
{
Error_code = "-1",
Error_msg = ex.Message
};
}
}
/// <summary>
/// 使用Post的方式調(diào)用百度API進(jìn)行翻譯
/// </summary>
/// <param name="content">要轉(zhuǎn)化的文本</param>
/// <param name="languageFrom">要轉(zhuǎn)化的語言</param>
/// <param name="languageTo">目標(biāo)語言</param>
/// <returns></returns>
public static FeedbackResult TranslatePost(string content, string languageFrom, string languageTo)
{
string appId = "20230722001753350";
string passWord = "your password";
string randomNum = new Random().Next().ToString();
#region 獲取MD5加密編碼后的小寫格式文本
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] buffer = md5.ComputeHash(Encoding.UTF8.GetBytes(appId + content + randomNum + passWord));
string md5Sign = string.Join("", buffer.Select(x => x.ToString("x2")));//轉(zhuǎn)化為小寫
#endregion
try
{
WebClient webClient = new WebClient();
System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
nameValueCollection.Add("q", content);
nameValueCollection.Add("from", languageFrom);
nameValueCollection.Add("to", languageTo);
nameValueCollection.Add("appid", appId);
nameValueCollection.Add("salt", randomNum);
nameValueCollection.Add("sign", md5Sign);
string apiUrl = "http://api.fanyi.baidu.com/api/trans/vip/translate";
byte[] bytes = webClient.UploadValues(apiUrl, "POST", nameValueCollection);
string resultContent = Encoding.UTF8.GetString(bytes);
FeedbackResult feedbackResult = new JavaScriptSerializer().Deserialize<FeedbackResult>(resultContent);
feedbackResult.ResponseJson = resultContent;
return feedbackResult;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return new FeedbackResult()
{
Error_code = "-1",
Error_msg = ex.Message
};
}
}
}
/// <summary>
/// 反饋結(jié)果類
/// </summary>
public class FeedbackResult
{
/// <summary>
/// 錯(cuò)誤號(hào),翻譯出錯(cuò)時(shí)有此項(xiàng),翻譯成功時(shí)該項(xiàng)為null
/// </summary>
public string Error_code { set; get; }
/// <summary>
/// 錯(cuò)誤消息,翻譯出錯(cuò)時(shí)代表出錯(cuò)信息,翻譯成功時(shí)該項(xiàng)為null
/// </summary>
public string Error_msg { set; get; }
/// <summary>
/// 起始語言
/// </summary>
public string From { set; get; }
/// <summary>
/// 目標(biāo)語言
/// </summary>
public string To { set; get; }
/// <summary>
/// 響應(yīng)的源Json字符串,自定義項(xiàng)
/// </summary>
public string ResponseJson { set; get; }
/// <summary>
/// 翻譯結(jié)果,翻譯失敗時(shí)該項(xiàng)為null,翻譯成功時(shí)按照換行符"\n"來分割的數(shù)組,元組數(shù)據(jù)
/// </summary>
public TranslateResult[] Trans_result { set; get; }
}
/// <summary>
/// 翻譯結(jié)果類
/// </summary>
public class TranslateResult
{
/// <summary>
/// 源文本 Source
/// </summary>
public string Src { set; get; }
/// <summary>
/// 翻譯后的文本 Destination
/// </summary>
public string Dst { set; get; }
}
/// <summary>
/// 語言枚舉常數(shù)
/// </summary>
public class Language
{
public const string 自動(dòng)檢測(cè) = "auto";
public const string 中文 = "zh";
public const string 英語 = "en";
public const string 粵語 = "yue";
public const string 文言文 = "wyw";
public const string 日語 = "jp";
public const string 韓語 = "kor";
public const string 法語 = "fra";
public const string 西班牙語 = "spa";
public const string 泰語 = "th";
public const string 阿拉伯語 = "ara";
public const string 俄語 = "ru";
public const string 葡萄牙語 = "pt";
public const string 德語 = "de";
public const string 意大利語 = "it";
public const string 希臘語 = "el";
public const string 荷蘭語 = "nl";
public const string 波蘭語 = "pl";
public const string 保加利亞語 = "bul";
public const string 愛沙尼亞語 = "est";
public const string 丹麥語 = "dan";
public const string 芬蘭語 = "fin";
public const string 捷克語 = "cs";
public const string 羅馬尼亞語 = "rom";
public const string 斯洛文尼亞語 = "slo";
public const string 瑞典語 = "swe";
public const string 匈牙利語 = "hu";
public const string 繁體中文 = "cht";
public const string 越南語 = "vie";
}
}
三、窗體FormTranslator測(cè)試程序如下:
文件FormTranslator.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TranslatorDemo
{
public partial class FormTranslator : Form
{
public FormTranslator()
{
InitializeComponent();
/*string test = @"上料X軸 錯(cuò)誤
上料X軸 伺服錯(cuò)誤
上料X軸 手自動(dòng)沖突
上料Y軸 錯(cuò)誤
上料Y軸 伺服錯(cuò)誤
上料Y軸 手自動(dòng)沖突
上料Z軸 錯(cuò)誤
上料Z軸 伺服錯(cuò)誤
上料Z軸 手自動(dòng)沖突
上料模組取料夾爪氣缸 原位報(bào)警
上料模組取料夾爪氣缸 動(dòng)位報(bào)警
上料模組取料夾爪氣缸 手自動(dòng)沖突
上料模組取料夾爪氣缸 錯(cuò)誤
上料模組升降氣缸 原位報(bào)警
上料模組升降氣缸 動(dòng)位報(bào)警
上料模組升降氣缸 手自動(dòng)沖突
上料模組升降氣缸 錯(cuò)誤
上料模組滑臺(tái)氣缸 原位報(bào)警
上料模組滑臺(tái)氣缸 動(dòng)位報(bào)警
上料模組滑臺(tái)氣缸 手自動(dòng)沖突
上料模組滑臺(tái)氣缸 錯(cuò)誤
上料模組 取料失敗
上料模組 中途掉料
上料模組 夾爪放料報(bào)警
上料模組 夾爪取料報(bào)警";
string english = @"message queue
death knight
sword seven
the move speed is 200 mm/s
thunder bird";*/
}
private void bntToEnglish_Click(object sender, EventArgs e)
{
rtxtEnglish.Clear();
FeedbackResult feedbackResult = TranslateUtil.TranslatePost(rtxtChinese.Text.Trim(), Language.中文, Language.英語);
TranslateResult[] contents = feedbackResult.Trans_result;
for (int i = 0; contents != null && i < contents.Length; i++)
{
rtxtEnglish.AppendText($"【{contents[i].Dst}】<-【{contents[i].Src}】\n");
}
rtxtEnglish.AppendText($"響應(yīng)的源Json數(shù)據(jù)為:\n{feedbackResult.ResponseJson}");
}
private void btnToChinese_Click(object sender, EventArgs e)
{
rtxtChinese.Clear();
FeedbackResult feedbackResult = TranslateUtil.TranslateGet(rtxtEnglish.Text.Trim(), Language.英語, Language.中文);
TranslateResult[] contents = feedbackResult.Trans_result;
for (int i = 0; contents != null && i < contents.Length; i++)
{
rtxtChinese.AppendText($"【{contents[i].Dst}】<-【{contents[i].Src}】\n");
}
rtxtChinese.AppendText($"響應(yīng)的源Json數(shù)據(jù)為:\n{feedbackResult.ResponseJson}");
}
}
}
四、測(cè)試運(yùn)行如圖:
【需要到百度上申請(qǐng)開發(fā)者賬號(hào)appId和密碼password】
①中文--->英文
?②英文--->中文
文章來源:http://www.zghlxwxcb.cn/news/detail-634352.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-634352.html
到了這里,關(guān)于C#調(diào)用百度翻譯API自動(dòng)將中文轉(zhuǎn)化為英文,按行轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!