Created
August 2, 2014 06:52
-
-
Save yorkie/31c2c5c1691c7ef24000 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
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
copied from https://github.com/lepture/opencc-python/blob/master/opencc/_opencc.py