simpleseg.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from itertools import chain
  4. from pypinyin.compat import text_type, bytes_type
  5. from pypinyin.constants import RE_HANS, PHRASES_DICT
  6. from pypinyin.seg import mmseg
  7. def seg(hans):
  8. hans = simple_seg(hans)
  9. ret = []
  10. for x in hans:
  11. if not RE_HANS.match(x): # 没有拼音的字符,不再参与二次分词
  12. ret.append(x)
  13. elif PHRASES_DICT:
  14. ret.extend(list(mmseg.seg.cut(x)))
  15. else: # 禁用了词语库,不分词
  16. ret.append(x)
  17. return ret
  18. def simple_seg(hans):
  19. """将传入的字符串按是否是汉字来分割"""
  20. assert not isinstance(hans, bytes_type), \
  21. 'must be unicode string or [unicode, ...] list'
  22. if isinstance(hans, text_type):
  23. return _seg(hans)
  24. else:
  25. hans = list(hans)
  26. if len(hans) == 1:
  27. return simple_seg(hans[0])
  28. return list(chain(*[simple_seg(x) for x in hans]))
  29. def _seg(chars):
  30. """按是否是汉字进行分词"""
  31. s = '' # 保存一个词
  32. ret = [] # 分词结果
  33. flag = 0 # 上一个字符是什么? 0: 汉字, 1: 不是汉字
  34. for n, c in enumerate(chars):
  35. if RE_HANS.match(c): # 汉字, 确定 flag 的初始值
  36. if n == 0: # 第一个字符
  37. flag = 0
  38. if flag == 0:
  39. s += c
  40. else: # 上一个字符不是汉字, 分词
  41. ret.append(s)
  42. flag = 0
  43. s = c
  44. else: # 不是汉字
  45. if n == 0: # 第一个字符, 确定 flag 的初始值
  46. flag = 1
  47. if flag == 1:
  48. s += c
  49. else: # 上一个字符是汉字, 分词
  50. ret.append(s)
  51. flag = 1
  52. s = c
  53. ret.append(s) # 最后的词
  54. return ret