__init__.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # -*- coding: utf-8 -*-
  2. from functools import wraps
  3. # 存储各拼音风格对应的实现
  4. _registry = {}
  5. def convert(pinyin, style, strict, default=None, **kwargs):
  6. """根据拼音风格把原始拼音转换为不同的格式
  7. :param pinyin: 原始有声调的单个拼音
  8. :type pinyin: unicode
  9. :param style: 拼音风格
  10. :param strict: 只获取声母或只获取韵母相关拼音风格的返回结果
  11. 是否严格遵照《汉语拼音方案》来处理声母和韵母,
  12. 详见 :ref:`strict`
  13. :type strict: bool
  14. :param default: 拼音风格对应的实现不存在时返回的默认值
  15. :param kwargs: 兼容后续可能会新增的关键字参数。当前包含如下关键字参数:
  16. ``han``: 当前拼音对应的原始汉字。
  17. :return: 按照拼音风格进行处理过后的拼音字符串
  18. :rtype: unicode
  19. """
  20. if style in _registry:
  21. return _registry[style](pinyin, strict=strict, **kwargs)
  22. return default
  23. def register(style, func=None):
  24. """注册一个拼音风格实现。
  25. 自定义的函数应当使用 ``**kwargs`` 来兼容后续可能会新增的关键字参数,
  26. 当前默认会传递如下参数:
  27. * ``pinyin``: 原始有声调的单个拼音
  28. * ``strict``: 是否开启 strict 模式
  29. * ``han``: 当前拼音对应的原始汉字
  30. ::
  31. @register('echo')
  32. def echo(pinyin, **kwargs):
  33. return pinyin
  34. # or
  35. register('echo', echo)
  36. """
  37. if func is not None:
  38. _registry[style] = func
  39. return
  40. def decorator(func):
  41. _registry[style] = func
  42. @wraps(func)
  43. def wrapper(pinyin, **kwargs):
  44. return func(pinyin, **kwargs)
  45. return wrapper
  46. return decorator
  47. def auto_discover():
  48. """自动注册内置的拼音风格实现"""
  49. from pypinyin.style import ( # noqa
  50. initials,
  51. tone,
  52. finals,
  53. bopomofo,
  54. cyrillic,
  55. wadegiles,
  56. others,
  57. gwoyeu,
  58. braille_mainland,
  59. )