Quick tips for conversion between Traditional Chinese and Simplified Chinese (繁簡轉換)

Dave Wong
2 min readDec 18, 2020

TLDR

Open Chinese Convert — opencc https://github.com/BYVoid/OpenCC

opencc is a powerful conversion tools among TC, SC and Japanese Kanji (Not sure what it is, just copied from above github webpage). Please find the detailed description in the official readme.

You may find some official supported language libraries or packages. In some cases if your systems are not implemented with supported languages, you can try to install the executable package in the OS, then use your program language to invoke the command to do the conversion.

In my case, my website was implemented by Symfony (PHP framework). The web server were installed in Debian. The conversion finally works by calling /usr/bin/opencc with Symfony\Component\Process. Codes show below (opencc CLI should be installed in OS):

use Symfony\Component\Process\Process;
$process = new Process(['opencc', '-c hk2s.json']);
$process->setInput("香港繁體到簡體\n<pre>並轉換爲臺灣常用詞彙</pre>\n<p>臺灣正體到繁體</p>");
$code = $process->run();
if (!$process->isSuccessful()) {
// raise exception or do what you want
}
echo $process->getOutput();
echo "\n";
$process->setInput('你好嗎?');
$code = $process->run();
echo $process->getOutput();

Few points to note:

  1. Config file (eg. hk2s.json) is required for it to work properly
  2. Input with multiple lines for each conversion works well. (Sounds normal? Try the CLI in shell with stdin may confuse you)
  3. Behavior of Process class: run should be call every time, but no re-initialize the instance is required.

Alternative(s) in PHP world:

This PHP package does not work in my case due to the Symfony framework version conflict. For those who use Laravel and latest Symfony, it is definitely worth to give a try.

To invoke the command, exec, shell_exec and proc_open etc. may work well. In my case, I have Symfony and Symfony\Component\Process is handy. I saved time and made the codes concise without using above PHP functions.

Please feel free to comment.

如需要中文解釋,請告知。

--

--

Dave Wong
0 Followers

An IT geek loves programming, DevOps and cloud solutions