【NET】使用结巴分词检索

结巴分词的源码:jieba中文分词

在一個检索系统中,使用了结巴分词来进行分词检索,感觉很方便。

首先,把结巴分词的词库写入到数据库中,用来判断检索的关键字是否为新词,
如果新词的话,就直接like整篇文章,再保存检索关键字到词库和分词表中;
不是的话,就在分词表中进行搜索,这样检索速度就增加了,也不会出现检索不到词的问题。

接在修改结巴分词的源码

修改加载词库的方法:WordDictionary.cs中LoadDict的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
private void LoadDict()
{
try
{
var stopWatch = new Stopwatch();
stopWatch.Start();
// 从SQL中读取数据
DBEntities db = new DBEntities();
var dt = db.ThesaurusList().ToList();
if (dt != null && dt.Any())
{
foreach (var item in dt)
{
var word = e.Convert.ToString(item.Text);
int freq = 0;
if (item.Frequency.HasValue)
freq = item.Frequency.Value;
Trie[word] = freq;
Total += freq;
foreach (var ch in Enumerable.Range(0, word.Length))
{
var wfrag = word.Sub(0, ch + 1);
if (!Trie.ContainsKey(wfrag))
{
Trie[wfrag] = 0;
}
}
}
}
stopWatch.Stop();
Debug.WriteLine("main dict load finished, time elapsed {0} ms", stopWatch.ElapsedMilliseconds);
}
catch (IOException e)
{
Debug.Fail(string.Format("{0} load failure, reason: {1}", MainDict, e.Message));
}
catch (FormatException fe)
{
Debug.Fail(fe.Message);
}
}

增加添加新词的方法

1
2
3
4
5
6
7
8
public void SqlDtAdd(string word, int freq, string tag = null)
{
if (!ContainsWord(word))
{
DBEntities db = new DBEntities();
db.ThesaurusAdd(word, tag, freq);
}
}

增加接口调用的方法:在JiebaSegmenter.cs中增加以下两个方法,用于判断分词是否存在并添加新词

1
2
3
4
5
6
7
8
9
10
public void SqlDtAdd(string word, int freq = 0, string tag = null)
{
WordDict.SqlDtAdd(word, freq, tag);
AddWord(word, freq, tag);
}
public bool SqlDtContainsWord(string text)
{
return WordDict.ContainsWord(text);
}