|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | + hangulize |
| 4 | + ~~~~~~~~~ |
| 5 | +
|
| 6 | + Korean Alphabet Transcription. |
| 7 | +
|
| 8 | + :copyright: (c) 2010-2017 by Heungsub Lee |
| 9 | + :license: BSD, see LICENSE for more details. |
| 10 | +""" |
| 11 | +from __future__ import absolute_import |
| 12 | +import importlib |
| 13 | + |
| 14 | + |
| 15 | +__version__ = '0.0.9' |
| 16 | +__all__ = ['hangulize', 'get_lang', 'supports'] |
| 17 | + |
| 18 | + |
| 19 | +def hangulize(string, code=None): |
| 20 | + """Transcribes a loanword to Hangul. |
| 21 | +
|
| 22 | + >>> print hangulize(u'gloria', 'ita') |
| 23 | + 글로리아 |
| 24 | +
|
| 25 | + :param string: a loan word |
| 26 | + :param code: a language code as ISO 639-3. if ``lang`` is not given, |
| 27 | + it is required |
| 28 | + """ |
| 29 | + return get_lang(code).hangulize(string) |
| 30 | + |
| 31 | + |
| 32 | +def get_lang(code): |
| 33 | + """Returns a language instance from the given code.""" |
| 34 | + code_head = code.split('.', 1)[0] |
| 35 | + if len(code_head) < 2 or len(code_head) > 3: |
| 36 | + raise ValueError('%r is an invalid language code' % code) |
| 37 | + def make_lang(code, submods): |
| 38 | + try: |
| 39 | + code = '.'.join([code] + list(submods)) |
| 40 | + return import_lang_module(code).__lang__() |
| 41 | + except ImportError: |
| 42 | + raise ValueError('Hangulize does not support %s' % code) |
| 43 | + # split module path |
| 44 | + if '.' in code: |
| 45 | + code = code.split('.') |
| 46 | + submods = code[1:] |
| 47 | + code = code[0] |
| 48 | + else: |
| 49 | + submods = () |
| 50 | + return make_lang(code, submods) |
| 51 | + |
| 52 | + |
| 53 | +def import_lang_module(code): |
| 54 | + """Imports a module from the given code.""" |
| 55 | + return importlib.import_module(f'kss._modules.hangulization.hangulize.langs.{code}') |
| 56 | + |
| 57 | + |
| 58 | +def supports(code): |
| 59 | + """Checks if hangulize supports the given language. |
| 60 | +
|
| 61 | + >>> supports('ita') |
| 62 | + True |
| 63 | + >>> supports('kat.narrow') |
| 64 | + True |
| 65 | + >>> supports('kor') |
| 66 | + False |
| 67 | + """ |
| 68 | + try: |
| 69 | + import_lang_module(code) |
| 70 | + return True |
| 71 | + except ImportError: |
| 72 | + return False |
| 73 | + |
| 74 | + |
| 75 | +def supported(code): |
| 76 | + """Deprecated with 0.0.6. Use :func:`hangulize.supports` instead.""" |
| 77 | + import warnings |
| 78 | + warnings.warn('supported() has been deprecated, use supports() instead', |
| 79 | + DeprecationWarning) |
| 80 | + return supports(code) |
| 81 | + |
| 82 | + |
| 83 | +# include all submodules. |
| 84 | +for name in ['.models', '.normalization', '.processing']: |
| 85 | + module = importlib.import_module(name, __name__) |
| 86 | + __all__.extend(module.__all__) |
| 87 | + for attr in module.__all__: |
| 88 | + locals()[attr] = getattr(module, attr) |
0 commit comments