
初始词典.jpg

翻译效果.jpg
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;
using System.IO;
namespace TranslateExample
{
public partial class Form1 : Form
{
//声明键值均为字符串的字典集合
Dictionary<string, string> dic = new Dictionary<string, string>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//将词典文件中的每壹行读入字符串数组
string[] contents = File.ReadAllLines("english.txt", Encoding.Default);
for (int i = 0; i < contents.Length; i++)
{
//词典文件中英文和中文对应格式为: 英文 中文1,中文2 或 英文 中文1 中文2 或 英文 中文3
//获得数组中每个元素(即一行英文和空格及中文字符串)中第一个空格
int index = contents[i].IndexOf(" ");
//截取空格之间的英文单词
string englishKey = contents[i].Substring(0, index);
//截取首个空格之后的其余空格和中文,再剔除空格
string chineseValue = contents[i].Substring(index + 1).Trim();
//dic.Add(english, chinese);
if (!dic.ContainsKey(englishKey))
{
dic.Add(englishKey, chineseValue);
}
else
{
//有重复的 累加给英文单词所对应的中文解释
dic[englishKey] += chineseValue;
}
#region 另外一种实现方式
//string[] temp = contents[i].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
//string chinese = string.Empty;
//for (int j = 1; j < temp.Length; j++)
//{
// chinese += temp[j];
//}
//添加之前做一个判断
//if (!dic.ContainsKey(temp[0]))
//{
// dic.Add(temp[0], chinese);
//}
//else
//{
// //有重复的 累加给英文单词所对应的中文解释
// dic[temp[0]] += chinese;
//}
#endregion
}
}
private void TranslateButton_Click(object sender, EventArgs e)
{
string english = EnglishTextBox.Text.Trim();
if (dic.ContainsKey(english))
{
ChineseTextBox.Text = dic[english];
}
else
{
ChineseTextBox.Text = "请下载最新版本的英文词典!!!";
}
}
}
}
网友评论