VicDict.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: tanszhe
  5. * Date: 2017/12/21
  6. * Time: 下午8:16
  7. * Url: https://github.com/lizhichao/VicWord
  8. */
  9. namespace addons\cms\library;
  10. class VicDict
  11. {
  12. private $word = [];
  13. /**
  14. * 词典地址
  15. * @var string
  16. */
  17. private $code = 'utf-8';
  18. private $end = ['\\' => 1];
  19. private $default_end = ['\\' => 1];
  20. private $end_key = '\\';
  21. private $type = 'igb';
  22. public function __construct($type = 'igb')
  23. {
  24. $this->type = $type;
  25. if (file_exists(_VIC_WORD_DICT_PATH_)) {
  26. if ($type == 'igb') {
  27. $this->word = igbinary_unserialize(file_get_contents(_VIC_WORD_DICT_PATH_));
  28. } else {
  29. $this->word = json_decode(file_get_contents(_VIC_WORD_DICT_PATH_), true);
  30. }
  31. }
  32. }
  33. /**
  34. * @param string $word
  35. * @param null|string $x 词性
  36. * @return bool
  37. */
  38. public function add($word, $x = null)
  39. {
  40. $this->end = ['\\x' => $x] + $this->default_end;
  41. $word = $this->filter($word);
  42. if ($word) {
  43. return $this->merge($word);
  44. }
  45. return false;
  46. }
  47. private function merge($word)
  48. {
  49. $ar = $this->toArr($word);
  50. $br = $ar;
  51. $wr = &$this->word;
  52. foreach ($ar as $i => $v) {
  53. array_shift($br);
  54. if (!isset($wr[$v])) {
  55. $wr[$v] = $this->dict($br, $this->end);
  56. return true;
  57. } else {
  58. $wr = &$wr[$v];
  59. }
  60. }
  61. if (!isset($wr[$this->end_key])) {
  62. foreach ($this->end as $k => $v) {
  63. $wr[$k] = $v;
  64. $wr[$k] = $v;
  65. }
  66. }
  67. return true;
  68. }
  69. public function save()
  70. {
  71. if ($this->type == 'igb') {
  72. $str = igbinary_serialize($this->word);
  73. } else {
  74. $str = json_encode($this->word);
  75. }
  76. return file_put_contents(_VIC_WORD_DICT_PATH_, $str);
  77. }
  78. private function filter($word)
  79. {
  80. return str_replace(["\n", "\t"], '', trim($word));
  81. }
  82. private function dict($arr, $v, $i = 0)
  83. {
  84. if (isset($arr[$i])) {
  85. return [$arr[$i] => $this->dict($arr, $v, $i + 1)];
  86. } else {
  87. return $v;
  88. }
  89. }
  90. private function toArr($str)
  91. {
  92. $l = mb_strlen($str, $this->code);
  93. $r = [];
  94. for ($i = 0; $i < $l; $i++) {
  95. $r[] = mb_substr($str, $i, 1, $this->code);
  96. }
  97. return $r;
  98. }
  99. }