• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mozillazg / python-pinyin / 119

pending completion
119

push

circle-ci

mozillazg
配置使用 CircleCI,不再测试 Python 2.6 和 Python 3.3,增加测试 PyPy3

275 of 527 relevant lines covered (52.18%)

0.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

27.72
/pypinyin/core.py
1
#!/usr/bin/env python
2
# -*- coding: utf-8 -*-
3

4
from __future__ import unicode_literals
1✔
5

6
from copy import deepcopy
1✔
7
from itertools import chain
1✔
8

9
from pypinyin.compat import text_type, callable_check
1✔
10
from pypinyin.constants import (
1✔
11
    PHRASES_DICT, PINYIN_DICT,
12
    RE_HANS, Style
13
)
14
from pypinyin.contrib import mmseg
1✔
15
from pypinyin.utils import simple_seg, _replace_tone2_style_dict_to_default
1✔
16
from pypinyin.style import auto_discover, convert as convert_style
1✔
17

18
auto_discover()
1✔
19

20

21
def seg(hans):
1✔
22
    hans = simple_seg(hans)
1✔
23
    ret = []
1✔
24
    for x in hans:
1✔
25
        if not RE_HANS.match(x):   # 没有拼音的字符,不再参与二次分词
1✔
26
            ret.append(x)
×
27
        elif PHRASES_DICT:
1✔
28
            ret.extend(list(mmseg.seg.cut(x)))
×
29
        else:   # 禁用了词语库,不分词
30
            ret.append(x)
1✔
31
    return ret
1✔
32

33

34
def load_single_dict(pinyin_dict, style='default'):
1✔
35
    """载入用户自定义的单字拼音库
36

37
    :param pinyin_dict: 单字拼音库。比如: ``{0x963F: u"ā,ē"}``
38
    :param style: pinyin_dict 参数值的拼音库风格. 支持 'default', 'tone2'
39
    :type pinyin_dict: dict
40
    """
41
    if style == 'tone2':
×
42
        for k, v in pinyin_dict.items():
×
43
            v = _replace_tone2_style_dict_to_default(v)
×
44
            PINYIN_DICT[k] = v
×
45
    else:
46
        PINYIN_DICT.update(pinyin_dict)
×
47

48
    mmseg.retrain(mmseg.seg)
×
49

50

51
def load_phrases_dict(phrases_dict, style='default'):
1✔
52
    """载入用户自定义的词语拼音库
53

54
    :param phrases_dict: 词语拼音库。比如: ``{u"阿爸": [[u"ā"], [u"bà"]]}``
55
    :param style: phrases_dict 参数值的拼音库风格. 支持 'default', 'tone2'
56
    :type phrases_dict: dict
57
    """
58
    if style == 'tone2':
×
59
        for k, value in phrases_dict.items():
×
60
            v = [
×
61
                list(map(_replace_tone2_style_dict_to_default, pys))
62
                for pys in value
63
            ]
64
            PHRASES_DICT[k] = v
×
65
    else:
66
        PHRASES_DICT.update(phrases_dict)
×
67

68
    mmseg.retrain(mmseg.seg)
×
69

70

71
def to_fixed(pinyin, style, strict=True):
1✔
72
    """根据拼音风格格式化带声调的拼音.
73

74
    :param pinyin: 单个拼音
75
    :param style: 拼音风格
76
    :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
77
    :return: 根据拼音风格格式化后的拼音字符串
78
    :rtype: unicode
79
    """
80
    return convert_style(pinyin, style=style, strict=strict, default=pinyin)
×
81

82

83
def _handle_nopinyin_char(chars, errors='default'):
1✔
84
    """处理没有拼音的字符"""
85
    if callable_check(errors):
×
86
        return errors(chars)
×
87

88
    if errors == 'default':
×
89
        return chars
×
90
    elif errors == 'ignore':
×
91
        return None
×
92
    elif errors == 'replace':
×
93
        if len(chars) > 1:
×
94
            return ''.join(text_type('%x' % ord(x)) for x in chars)
×
95
        else:
96
            return text_type('%x' % ord(chars))
×
97

98

99
def handle_nopinyin(chars, errors='default'):
1✔
100
    py = _handle_nopinyin_char(chars, errors=errors)
×
101
    if not py:
×
102
        return []
×
103
    if isinstance(py, list):
×
104
        return py
×
105
    else:
106
        return [py]
×
107

108

109
def single_pinyin(han, style, heteronym, errors='default', strict=True):
1✔
110
    """单字拼音转换.
111

112
    :param han: 单个汉字
113
    :param errors: 指定如何处理没有拼音的字符,详情请参考
114
                   :py:func:`~pypinyin.pinyin`
115
    :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
116
    :return: 返回拼音列表,多音字会有多个拼音项
117
    :rtype: list
118
    """
119
    num = ord(han)
×
120
    # 处理没有拼音的字符
121
    if num not in PINYIN_DICT:
×
122
        return handle_nopinyin(han, errors=errors)
×
123

124
    pys = PINYIN_DICT[num].split(',')  # 字的拼音列表
×
125
    if not heteronym:
×
126
        return [to_fixed(pys[0], style, strict=strict)]
×
127

128
    # 输出多音字的多个读音
129
    # 临时存储已存在的拼音,避免多音字拼音转换为非音标风格出现重复。
130
    # TODO: change to use set
131
    # TODO: add test for cache
132
    py_cached = {}
×
133
    pinyins = []
×
134
    for i in pys:
×
135
        py = to_fixed(i, style, strict=strict)
×
136
        if py in py_cached:
×
137
            continue
×
138
        py_cached[py] = py
×
139
        pinyins.append(py)
×
140
    return pinyins
×
141

142

143
def phrase_pinyin(phrase, style, heteronym, errors='default', strict=True):
1✔
144
    """词语拼音转换.
145

146
    :param phrase: 词语
147
    :param errors: 指定如何处理没有拼音的字符
148
    :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母
149
    :return: 拼音列表
150
    :rtype: list
151
    """
152
    py = []
×
153
    if phrase in PHRASES_DICT:
×
154
        py = deepcopy(PHRASES_DICT[phrase])
×
155
        for idx, item in enumerate(py):
×
156
            py[idx] = [to_fixed(item[0], style=style, strict=strict)]
×
157
    else:
158
        for i in phrase:
×
159
            single = single_pinyin(i, style=style, heteronym=heteronym,
×
160
                                   errors=errors, strict=strict)
161
            if single:
×
162
                py.append(single)
×
163
    return py
×
164

165

166
def _pinyin(words, style, heteronym, errors, strict=True):
1✔
167
    """
168
    :param words: 经过分词处理后的字符串,只包含中文字符或只包含非中文字符,
169
                  不存在混合的情况。
170
    """
171
    pys = []
×
172
    # 初步过滤没有拼音的字符
173
    if RE_HANS.match(words):
×
174
        pys = phrase_pinyin(words, style=style, heteronym=heteronym,
×
175
                            errors=errors, strict=strict)
176
        return pys
×
177

178
    py = handle_nopinyin(words, errors=errors)
×
179
    if py:
×
180
        pys.append(py)
×
181
    return pys
×
182

183

184
def pinyin(hans, style=Style.TONE, heteronym=False,
1✔
185
           errors='default', strict=True):
186
    """将汉字转换为拼音.
187

188
    :param hans: 汉字字符串( ``'你好吗'`` )或列表( ``['你好', '吗']`` ).
189
                 可以使用自己喜爱的分词模块对字符串进行分词处理,
190
                 只需将经过分词处理的字符串列表传进来就可以了。
191
    :type hans: unicode 字符串或字符串列表
192
    :param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.TONE` 风格。
193
                  更多拼音风格详见 :class:`~pypinyin.Style`
194
    :param errors: 指定如何处理没有拼音的字符
195

196
                   * ``'default'``: 保留原始字符
197
                   * ``'ignore'``: 忽略该字符
198
                   * ``'replace'``: 替换为去掉 ``\\u`` 的 unicode 编码字符串
199
                     (``'\\u90aa'`` => ``'90aa'``)
200
                   * callable 对象: 回调函数之类的可调用对象。如果 ``errors``
201
                     参数 的值是个可调用对象,那么程序会回调这个函数:
202
                     ``func(char)``::
203

204
                         def foobar(char):
205
                             return 'a'
206
                         pinyin('あ', errors=foobar)
207

208
    :param heteronym: 是否启用多音字
209
    :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict`
210
    :return: 拼音列表
211
    :rtype: list
212

213
    :raise AssertionError: 当传入的字符串不是 unicode 字符时会抛出这个异常
214

215
    Usage::
216

217
      >>> from pypinyin import pinyin, Style
218
      >>> import pypinyin
219
      >>> pinyin('中心')
220
      [['zhōng'], ['xīn']]
221
      >>> pinyin('中心', heteronym=True)  # 启用多音字模式
222
      [['zhōng', 'zhòng'], ['xīn']]
223
      >>> pinyin('中心', style=Style.FIRST_LETTER)  # 设置拼音风格
224
      [['z'], ['x']]
225
      >>> pinyin('中心', style=Style.TONE2)
226
      [['zho1ng'], ['xi1n']]
227
      >>> pinyin('中心', style=Style.CYRILLIC)
228
      [['чжун1'], ['синь1']]
229
    """
230
    # 对字符串进行分词处理
231
    if isinstance(hans, text_type):
×
232
        han_list = seg(hans)
×
233
    else:
234
        han_list = chain(*(seg(x) for x in hans))
×
235
    pys = []
×
236
    for words in han_list:
×
237
        pys.extend(_pinyin(words, style, heteronym, errors, strict=strict))
×
238
    return pys
×
239

240

241
def slug(hans, style=Style.NORMAL, heteronym=False, separator='-',
1✔
242
         errors='default', strict=True):
243
    """生成 slug 字符串.
244

245
    :param hans: 汉字
246
    :type hans: unicode or list
247
    :param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。
248
                  更多拼音风格详见 :class:`~pypinyin.Style`
249
    :param heteronym: 是否启用多音字
250
    :param separstor: 两个拼音间的分隔符/连接符
251
    :param errors: 指定如何处理没有拼音的字符,详情请参考
252
                   :py:func:`~pypinyin.pinyin`
253
    :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict`
254
    :return: slug 字符串.
255

256
    :raise AssertionError: 当传入的字符串不是 unicode 字符时会抛出这个异常
257

258
    ::
259

260
      >>> import pypinyin
261
      >>> from pypinyin import Style
262
      >>> pypinyin.slug('中国人')
263
      'zhong-guo-ren'
264
      >>> pypinyin.slug('中国人', separator=' ')
265
      'zhong guo ren'
266
      >>> pypinyin.slug('中国人', style=Style.FIRST_LETTER)
267
      'z-g-r'
268
      >>> pypinyin.slug('中国人', style=Style.CYRILLIC)
269
      'чжун1-го2-жэнь2'
270
    """
271
    return separator.join(chain(*pinyin(hans, style=style, heteronym=heteronym,
×
272
                                        errors=errors, strict=strict)
273
                                ))
274

275

276
def lazy_pinyin(hans, style=Style.NORMAL, errors='default', strict=True):
1✔
277
    """不包含多音字的拼音列表.
278

279
    与 :py:func:`~pypinyin.pinyin` 的区别是返回的拼音是个字符串,
280
    并且每个字只包含一个读音.
281

282
    :param hans: 汉字
283
    :type hans: unicode or list
284
    :param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。
285
                  更多拼音风格详见 :class:`~pypinyin.Style`。
286
    :param errors: 指定如何处理没有拼音的字符,详情请参考
287
                   :py:func:`~pypinyin.pinyin`
288
    :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict`
289
    :return: 拼音列表(e.g. ``['zhong', 'guo', 'ren']``)
290
    :rtype: list
291

292
    :raise AssertionError: 当传入的字符串不是 unicode 字符时会抛出这个异常
293

294
    Usage::
295

296
      >>> from pypinyin import lazy_pinyin, Style
297
      >>> import pypinyin
298
      >>> lazy_pinyin('中心')
299
      ['zhong', 'xin']
300
      >>> lazy_pinyin('中心', style=Style.TONE)
301
      ['zhōng', 'xīn']
302
      >>> lazy_pinyin('中心', style=Style.FIRST_LETTER)
303
      ['z', 'x']
304
      >>> lazy_pinyin('中心', style=Style.TONE2)
305
      ['zho1ng', 'xi1n']
306
      >>> lazy_pinyin('中心', style=Style.CYRILLIC)
307
      ['чжун1', 'синь1']
308
    """
309
    return list(chain(*pinyin(hans, style=style, heteronym=False,
×
310
                              errors=errors, strict=strict)))
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2024 Coveralls, Inc