Skip to content

Instantly share code, notes, and snippets.

@yorkie
Created August 2, 2014 06:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yorkie/31c2c5c1691c7ef24000 to your computer and use it in GitHub Desktop.
Save yorkie/31c2c5c1691c7ef24000 to your computer and use it in GitHub Desktop.
import os
from ctypes.util import find_library
from ctypes import CDLL, cast, c_char_p, c_int, c_size_t, c_void_p
_libcfile = find_library('c') or 'libc.so.6'
libc = CDLL(_libcfile, use_errno=True)
_libopenccfile = os.environ.get('LIBOPENCC') or find_library('opencc')
if _libopenccfile:
libopencc = CDLL(_libopenccfile, use_errno=True)
else:
libopencc = CDLL('libopencc.so.1', use_errno=True)
libc.free.argtypes = [c_void_p]
libopencc.opencc_open.restype = c_void_p
libopencc.opencc_convert_utf8.argtypes = [c_void_p, c_char_p, c_size_t]
libopencc.opencc_convert_utf8.restype = c_void_p
libopencc.opencc_close.argtypes = [c_void_p]
libopencc.opencc_perror.argtypes = [c_char_p]
libopencc.opencc_dict_load.argtypes = [c_void_p, c_char_p, c_int]
CONFIGS = [
'zhs2zhtw_p.ini', 'zhs2zhtw_v.ini', 'zhs2zhtw_vp.ini',
'zht2zhtw_p.ini', 'zht2zhtw_v.ini', 'zht2zhtw_vp.ini',
'zhtw2zhs.ini', 'zhtw2zht.ini', 'zhtw2zhcn_s.ini', 'zhtw2zhcn_t.ini',
'zhs2zht.ini', 'zht2zhs.ini',
]
def convert(text, config='zht2zhs.ini'):
assert config in CONFIGS
od = libopencc.opencc_open(c_char_p(config))
retv_i = libopencc.opencc_convert_utf8(od, text, len(text))
if retv_i == -1:
raise Exception('OpenCC Convert Error')
retv_c = cast(retv_i, c_char_p)
value = retv_c.value
libc.free(retv_c)
libopencc.opencc_close(od)
return value
@yorkie
Copy link
Author

yorkie commented Aug 2, 2014

@yorkie
Copy link
Author

yorkie commented Aug 2, 2014

test:

# coding=utf-8
from opencc import convert
print convert('簡體到繁體')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment