改为本地字典

This commit is contained in:
2026-04-12 04:24:35 +08:00
parent 7e32b19a91
commit 04bba673de
12 changed files with 621728 additions and 1 deletions
+16 -1
View File
@@ -9,6 +9,7 @@ import (
"encoding/json" // JSON 反序列化(加载屏蔽词列表)
"math" // 数学运算(最小值、开方)
"os" // 文件系统操作(读取屏蔽词文件)
"path/filepath" // 路径处理
"strings" // 字符串操作
"sync" // 互斥锁(保护 jieba 的非线程安全调用)
"unicode" // Unicode 字符判断
@@ -76,7 +77,21 @@ type Analyzer struct {
// stopWordsPath:屏蔽词 JSON 文件路径(不含文件时传入空字符串)。
func New(modelPath, stopWordsPath string) (*Analyzer, error) {
// 初始化结巴分词(加载词典,需调用 Free 释放)
j := gojieba.NewJieba()
// 词典路径:优先使用 ./dict/,否则回退到 go module 缓存
dictPath := filepath.Join(".", "dict")
jiebaDict := filepath.Join(dictPath, "jieba.dict.utf8")
hmmModel := filepath.Join(dictPath, "hmm_model.utf8")
posDict := filepath.Join(dictPath, "pos_dict.utf8")
idenDict := filepath.Join(dictPath, "iden_dict.utf8")
var j *gojieba.Jieba
if _, err := os.Stat(jiebaDict); err == nil {
// 词典存在,使用本地路径
j = gojieba.NewJieba(jiebaDict, hmmModel, posDict, idenDict)
} else {
// 词典不存在,使用默认路径(go module 缓存)
j = gojieba.NewJieba()
}
// 构建 lingua 语言检测器,覆盖所有 75 种语言(含中日韩英等)
// MinimumRelativeDistance=0.15:降低检测阈值,提高短文本召回率