// 简繁转换 - 绿色工具箱 // 词典数据来自 OpenCC(Apache License 2.0),嵌入 exe 资源,单文件离线 // 算法:词组最长匹配优先,未命中段回落到单字映射 // C# 5.0 语法,零第三方依赖 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Reflection; using System.Text; using System.Windows.Forms; namespace GreenTool { public class S2TForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private TextBox txtIn, txtOut; private RadioButton rbS2T, rbT2S; private Button btnConvert, btnCopy, btnOpen, btnSaveOut; private Label lblStatus; private string currentFile = ""; // 词典:词组表(用于最长匹配)+ 单字表 private Dictionary phraseMap; private Dictionary charMap; private int maxPhraseLen; public S2TForm() { InitUi(); LoadDicts(); } private void InitUi() { this.Text = "简繁转换 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = Color.White; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(760, 560); this.AllowDrop = true; this.DragEnter += new DragEventHandler(OnDragEnter); this.DragDrop += new DragEventHandler(OnDragDrop); int x = 16, y = 14; rbS2T = new RadioButton(); rbS2T.Text = "简体 → 繁体"; rbS2T.Checked = true; rbS2T.Location = new Point(x, y + 4); rbS2T.AutoSize = true; this.Controls.Add(rbS2T); rbT2S = new RadioButton(); rbT2S.Text = "繁体 → 简体"; rbT2S.Location = new Point(x + 120, y + 4); rbT2S.AutoSize = true; this.Controls.Add(rbT2S); btnConvert = MkBtn("开始转换", x + 240, y, 100, true); btnConvert.Click += new EventHandler(ConvertClick); btnOpen = MkBtn("打开文本文件…", x + 352, y, 120, false); btnOpen.Click += new EventHandler(OpenClick); Label lh = new Label(); lh.Text = "词典:OpenCC,离线可用"; lh.AutoSize = true; lh.Location = new Point(x + 490, y + 8); lh.ForeColor = COL_GRAY; this.Controls.Add(lh); y += 40; Label li = new Label(); li.Text = "原文(也可把 txt 文件拖进窗口):"; li.AutoSize = true; li.Location = new Point(x, y); this.Controls.Add(li); y += 22; txtIn = MkBox(x, y, 728, 180); y += 192; btnCopy = MkBtn("↑ 复制结果到剪贴板", x, y, 170, false); btnCopy.Click += new EventHandler(delegate(object s, EventArgs e) { if (txtOut.Text.Length > 0) Clipboard.SetText(txtOut.Text); }); btnSaveOut = MkBtn("结果另存为…", x + 182, y, 110, false); btnSaveOut.Click += new EventHandler(SaveOutClick); y += 34; Label lo = new Label(); lo.Text = "转换结果:"; lo.AutoSize = true; lo.Location = new Point(x, y); this.Controls.Add(lo); y += 22; txtOut = MkBox(x, y, 728, 180); txtOut.ReadOnly = true; txtOut.BackColor = Color.FromArgb(246, 250, 247); y += 192; lblStatus = new Label(); lblStatus.Text = "词组优先匹配,再逐字转换;未收录的字保持原样。"; lblStatus.Location = new Point(x, y); lblStatus.AutoSize = true; lblStatus.ForeColor = COL_GRAY; this.Controls.Add(lblStatus); } private TextBox MkBox(int px, int py, int w, int h) { TextBox t = new TextBox(); t.Location = new Point(px, py); t.Size = new Size(w, h); t.Multiline = true; t.ScrollBars = ScrollBars.Vertical; t.WordWrap = false; t.Font = new Font("Microsoft YaHei UI", 10f); this.Controls.Add(t); return t; } private Button MkBtn(string text, int px, int py, int w, bool primary) { Button b = new Button(); b.Text = text; b.Location = new Point(px, py); b.Size = new Size(w, 30); if (primary) { b.BackColor = COL_GREEN; b.ForeColor = Color.White; b.FlatStyle = FlatStyle.Flat; b.FlatAppearance.BorderSize = 0; } this.Controls.Add(b); return b; } // ---------------- 词典加载 ---------------- private string ReadResource(string name) { Assembly asm = Assembly.GetExecutingAssembly(); string ns = typeof(S2TForm).Namespace; using (Stream s = asm.GetManifestResourceStream(ns + ".data." + name)) { if (s == null) return ""; using (StreamReader r = new StreamReader(s, Encoding.UTF8)) { return r.ReadToEnd(); } } } private void LoadDicts() { phraseMap = new Dictionary(); charMap = new Dictionary(); maxPhraseLen = 0; try { LoadOne(ReadResource("STCharacters.txt"), true); LoadOne(ReadResource("STPhrases.txt"), false); LoadOne(ReadResource("TSCharacters.txt"), true); LoadOne(ReadResource("TSPhrases.txt"), false); lblStatus.Text = "词典已加载:词组 " + phraseMap.Count + " 条,单字 " + charMap.Count + " 组。"; } catch (Exception ex) { MessageBox.Show("词典加载失败:" + ex.Message); } } private void LoadOne(string content, bool isChar) { if (content.Length == 0) return; string[] lines = content.Split('\n'); foreach (string raw in lines) { string line = raw.TrimEnd('\r'); if (line.Length == 0) continue; int tab = line.IndexOf('\t'); if (tab <= 0) continue; string key = line.Substring(0, tab); string rest = line.Substring(tab + 1); int sp = rest.IndexOf(' '); string val = sp > 0 ? rest.Substring(0, sp) : rest; if (val.Length == 0) continue; if (isChar) { if (key.Length == 1 && !charMap.ContainsKey(key[0])) charMap[key[0]] = val; } else { if (!phraseMap.ContainsKey(key)) { phraseMap[key] = val; if (key.Length > maxPhraseLen) maxPhraseLen = key.Length; } } } } // ---------------- 转换核心 ---------------- // 方向:true=简→繁(用 ST*),false=繁→简(用 TS*)。 // 两个方向词典都装在同一个 map 里,靠 key 本身区分:先试词组再试单字, // 简体字/繁体字在 Unicode 上不重叠的部分自然互不干扰; // 重叠字形(如「干/乾/幹」类一对多)以 OpenCC 词典第一条为准。 private string ConvertText(string text, bool forward) { if (text.Length == 0) return ""; StringBuilder sb = new StringBuilder(text.Length + 16); int i = 0; while (i < text.Length) { int matched = 0; string mapped = null; // 词组最长匹配 int upper = maxPhraseLen; if (upper > text.Length - i) upper = text.Length - i; for (int len = upper; len >= 2; len--) { string seg = text.Substring(i, len); if (phraseMap.TryGetValue(seg, out mapped)) { matched = len; break; } } if (matched == 0) { char c = text[i]; if (charMap.TryGetValue(c, out mapped)) { // 单字表:同一张表里混着两个方向,若该字映射到自己则跳过 sb.Append(mapped.Length == 1 && mapped[0] == c ? c.ToString() : mapped); } else sb.Append(c); i++; } else { sb.Append(mapped); i += matched; } } return sb.ToString(); } // ---------------- 内置自测 ---------------- private static string[,] SelfTestCases() { // 逐条:输入 / 简转繁期望 / 繁转简期望 return new string[,] { { "简体中文", "簡體中文", "简体中文" }, { "我们在学习汉语。", "我們在學習漢語。", "我们在学习汉语。" }, { "软件", "軟件", "软件" }, { "头发", "頭髮", "头发" }, { " develop 123 abc ", " develop 123 abc ", " develop 123 abc " }, { "汉字", "漢字", "汉字" }, { "", "", "" } }; } public static int RunSelfTest() { S2TForm probe = new S2TForm(); string[,] tests = SelfTestCases(); int pass = 0; StringBuilder fail = new StringBuilder(); for (int i = 0; i < tests.GetLength(0); i++) { string gotS2T = probe.ConvertText(tests[i, 0], true); string gotT2S = probe.ConvertText(tests[i, 2] == "" ? "" : gotS2T, false); bool ok1 = gotS2T == tests[i, 1]; bool ok2 = tests[i, 2] == "" || gotT2S == tests[i, 2]; if (ok1 && ok2) pass++; else fail.AppendLine(tests[i, 0] + " → 简→繁「" + gotS2T + "」(期望 " + tests[i, 1] + ")" + (tests[i, 2] == "" ? "" : ";繁→简「" + gotT2S + "」(期望 " + tests[i, 2] + ")")); } string outPath = "selftest-s2t.txt"; File.WriteAllText(outPath, (pass == tests.GetLength(0) ? "ALL PASS " : "FAIL ") + pass + "/" + tests.GetLength(0) + "\r\n" + fail.ToString(), Encoding.UTF8); return pass == tests.GetLength(0) ? 0 : 1; } // ---------------- 事件 ---------------- private void ConvertClick(object sender, EventArgs e) { string src = txtIn.Text; if (src.Length == 0) { lblStatus.Text = "先粘贴要转换的文本。"; return; } txtOut.Text = ConvertText(src, rbS2T.Checked); lblStatus.Text = "转换完成," + src.Length + " 字 → " + txtOut.Text.Length + " 字。"; } private void OpenClick(object sender, EventArgs e) { using (OpenFileDialog d = new OpenFileDialog()) { d.Title = "打开文本文件"; d.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*"; if (d.ShowDialog() != DialogResult.OK) return; try { byte[] data = File.ReadAllBytes(d.FileName); Encoding enc; if (data.Length >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF) enc = new UTF8Encoding(true); else if (data.Length >= 2 && data[0] == 0xFF && data[1] == 0xFE) enc = Encoding.Unicode; else { try { new UTF8Encoding(false, true).GetString(data); enc = new UTF8Encoding(false); } catch { enc = Encoding.GetEncoding("GBK"); } } txtIn.Text = enc.GetString(data); currentFile = d.FileName; lblStatus.Text = Path.GetFileName(d.FileName) + " 已打开(" + enc.EncodingName + "),点「开始转换」。"; } catch (Exception ex) { lblStatus.Text = "打开失败:" + ex.Message; } } } private void SaveOutClick(object sender, EventArgs e) { if (txtOut.Text.Length == 0) { lblStatus.Text = "还没有转换结果。"; return; } using (SaveFileDialog d = new SaveFileDialog()) { d.Title = "结果另存为(UTF-8)"; d.Filter = "文本文件 (*.txt)|*.txt"; d.FileName = currentFile.Length > 0 ? Path.GetFileNameWithoutExtension(currentFile) + (rbS2T.Checked ? "-繁体" : "-简体") + ".txt" : "output.txt"; if (d.ShowDialog() != DialogResult.OK) return; File.WriteAllText(d.FileName, txtOut.Text, new UTF8Encoding(false)); lblStatus.Text = "已保存:" + d.FileName; } } private void OnDragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy; } private void OnDragDrop(object sender, DragEventArgs e) { string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; if (files == null || files.Length == 0) return; try { byte[] data = File.ReadAllBytes(files[0]); Encoding enc; if (data.Length >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF) enc = new UTF8Encoding(true); else if (data.Length >= 2 && data[0] == 0xFF && data[1] == 0xFE) enc = Encoding.Unicode; else { try { new UTF8Encoding(false, true).GetString(data); enc = new UTF8Encoding(false); } catch { enc = Encoding.GetEncoding("GBK"); } } txtIn.Text = enc.GetString(data); currentFile = files[0]; ConvertClick(this, EventArgs.Empty); } catch (Exception ex) { lblStatus.Text = "读取失败:" + ex.Message; } } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(S2TForm.RunSelfTest()); return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new S2TForm()); } } }