OpenCC 提供繁簡中文轉換,官方預編譯版 (0.4.2) 與 VS 相容性差。後發現 GitHub 最新版可直接用 CMake 生成 VS 專案,順利整合。
cmake -G "Visual Studio 12" -DCMAKE_INSTALL_PREFIX="" \
-DCMAKE_BUILD_TYPE=Release -DENABLE_GETTEXT:BOOL=OFF
opencc.sln,建置 libopencc 專案 (Release 版)。src/Release/:opencc.dll、opencc.lib。僅需四個檔案:
opencc.h、Export.hpp (標頭檔)opencc.lib (匯入庫)、opencc.dll (執行期)專案屬性 → C/C++ → Additional Include Directories 加入標頭目錄;Linker → Additional Library Directories 加入庫目錄;Linker → Input → Additional Dependencies 加入 opencc.lib。
#include "opencc.h"
#include
std::string sInput = "開發測試";
Opencc::SimpleConverter converter("s2t.json"); // 簡體→繁體配置
std::string sResult = converter.Convert(sInput); // 輸入需為 UTF-8
// sResult == "開發測試" (繁體)
配置檔 (如 s2t.json) 定義轉換鏈與字典。預設引用 .ocd 二進位字典,但也可直接使用文字字典 (.txt):
{
"name": "Simplified Chinese to Traditional Chinese",
"conversion_chain": [{
"type": "mmseg",
"dict": {
"type": "group",
"dicts": [
{"type": "text", "file": "STPhrases.txt"},
{"type": "text", "file": "STCharacters.txt"}
]
}
}]
}
將 s2t.json、STPhrases.txt、STCharacters.txt 放在執行目錄,初始化時即可讀取。反向轉換改用 t2s.json。
opencc_dict 工具轉換 .txt → .ocd 可能產生不可用檔案,建議直接用文字字典。