• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

dictionary.go

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
package sego

import "github.com/adamzy/cedar-go"

// Dictionary结构体实现了一个字串前缀树,一个分词可能出现在叶子节点也有可能出现在非叶节点
type Dictionary struct {
    trie           *cedar.Cedar // Cedar 前缀树
    maxTokenLength int          // 词典中最长的分词
    tokens         []Token      // 词典中所有的分词,方便遍历
    totalFrequency int64        // 词典中所有分词的频率之和
}

func NewDictionary() *Dictionary {
    return &Dictionary{trie: cedar.New()}
}

// 词典中最长的分词
func (dict *Dictionary) MaxTokenLength() int {
    return dict.maxTokenLength
}

// 词典中分词数目
func (dict *Dictionary) NumTokens() int {
    return len(dict.tokens)
}

// 词典中所有分词的频率之和
func (dict *Dictionary) TotalFrequency() int64 {
    return dict.totalFrequency
}

// 向词典中加入一个分词
func (dict *Dictionary) addToken(token Token) {
    bytes := textSliceToBytes(token.text)
    _, err := dict.trie.Get(bytes)
    if err == nil {
        return
    }

    dict.trie.Insert(bytes, dict.NumTokens())
    dict.tokens = append(dict.tokens, token)
    dict.totalFrequency += int64(token.frequency)
    if len(token.text) > dict.maxTokenLength {
        dict.maxTokenLength = len(token.text)
    }
}

// 在词典中查找和字元组words可以前缀匹配的所有分词
// 返回值为找到的分词数
func (dict *Dictionary) lookupTokens(words []Text, tokens []*Token) (numOfTokens int) {
    var id, value int
    var err error
    for _, word := range words {
        id, err = dict.trie.Jump(word, id)
        if err != nil {
            break
        }
        value, err = dict.trie.Value(id)
        if err == nil {
            tokens[numOfTokens] = &dict.tokens[value]
            numOfTokens++
        }
    }
    return
}


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
go-micro项目实战四 链路追踪发布时间:2022-07-10
下一篇:
图文直播:Pokémon Go真爱粉与“脑残粉”之间的爱恨情仇发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap