Open Chinese Convert(OpenCC)是一個開源的中文簡繁轉換項目,致力於製作高質量的基於統計預料的簡繁轉換詞庫。還提供函數庫(libopencc)、命令行簡繁轉換工具、人工校對工具、詞典生成程序、在線轉換服務及圖形用戶界面。
opencc的特點:
嚴格區分「一簡對多繁」、「一簡對多異」和「地域用詞差別」。
支持異體字轉換,兼容陸港澳臺等不同地區用字差別。
嚴格審校一簡對多繁詞條,原則爲「能分則不合」,用戶可自定義合併。
支持中國大陸、臺灣、香港異體字和地區習慣用詞轉換,如「裏」「裡」、「鼠標」「滑鼠」。
詞庫和函數庫完全分離,可以自由修改、導入、擴展。
支持C、C++、Python、PHP、Java、Ruby、Node.js and Android等多種語言API,提供命令行直接調用,以及圖形界面。
兼容Windows、Linux、Mac等多種平臺。
項目使用java編寫,官網說支持java語言,但是沒有找到java的api,所以使用曲折的方式實現:linux下安裝opencc,編寫shell腳本,然後使用java調用shell腳本來進行簡繁轉換。
opencc安裝請點擊 ubuntu安裝opencc,簡體轉繁體
opencc安裝後編寫shell腳本
#!/bin/sh #echo $1 echo $1 |opencc -c s2tw
測試:
ubuntu@ubuntu-vm:/usr/local$ ./s2tw.sh 微兒博客 微兒博客
java調用shell
public static Object sc2tw(String content){ try { StringBuffer sb = new StringBuffer(""); Process ps = Runtime.getRuntime().exec("/usr/local/s2tw.sh \""+content+"\""); BufferedReader in = new BufferedReader(new InputStreamReader(ps.getInputStream())); String line = null; ps.waitFor(); while((line = in.readLine())!=null){ sb.append(line); } in.close(); if(sb.indexOf("\"")==0){ sb = sb.deleteCharAt(0); } if(sb.lastIndexOf("\"")==sb.length()-1){ sb = sb.deleteCharAt(sb.length()-1); } ps.destroy(); line = null; return sb; } catch (IOException e) { logger.error("shell執行出錯"); } catch (InterruptedException e) { logger.error("shell執行出錯"); } return content; }
但是具體執行過程中發現java程序運行一段時間後會卡死,經過排查發現當shell腳本傳入的參數特別大時,java會一直等待shell腳本執行完成,所以對於長度特別長的文本採用分段轉換
public static String simple2tw(String content){ StringBuffer cs = new StringBuffer(""); int length = content.length(); int count = length/words; int ys = length%words; if (count==0) { cs.append(sc2tw(content)); }else{ for(int i=0;i<count;i++){ cs.append(sc2tw(content.substring(i*words, (i+1)*words))); length = (i+1)*words; } if(ys>0){ cs.append(sc2tw(content.substring(length))); } } return cs.toString(); }
本文轉載自 http://www.weare.net.cn/article/62eae88fa673b07361ba57cf79a0ed96.html