前言
基于詞典的正向最大匹配算法(最長詞優(yōu)先匹配),算法會根據(jù)詞典文件自動調(diào)整最大長度,分詞的好壞完全取決于詞典。
所謂詞典正向最大匹配就是將一段字符串進行分隔,其中分隔 的長度有限制,然后將分隔的子字符串與字典中的詞進行匹配,如果匹配成功則進行下一輪匹配,直到所有字符串處理完畢,否則將子字符串從末尾去除一個字,再進行匹配,如此反復(fù)。
算法流程圖如下:
下面給大家主要講一下中文分詞里面算法的簡單實現(xiàn),廢話不多說了,現(xiàn)在先上代碼
示例代碼
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
package com; import java.util.arraylist; import java.util.list; public class segmentation1 { private list<string> dictionary = new arraylist<string>(); private string request = "北京大學(xué)生前來應(yīng)聘" ; public void setdictionary() { dictionary.add( "北京" ); dictionary.add( "北京大學(xué)" ); dictionary.add( "大學(xué)" ); dictionary.add( "大學(xué)生" ); dictionary.add( "生前" ); dictionary.add( "前來" ); dictionary.add( "應(yīng)聘" ); } public string leftmax() { string response = "" ; string s = "" ; for ( int i= 0 ; i<request.length(); i++) { s += request.charat(i); if (isin(s, dictionary) && aheadcount(s, dictionary)== 1 ) { response += (s + "/" ); s = "" ; } else if (aheadcount(s, dictionary) > 0 ) { } else { response += (s + "/" ); s = "" ; } } return response; } private boolean isin(string s, list<string> list) { for ( int i= 0 ; i<list.size(); i++) { if (s.equals(list.get(i))) return true ; } return false ; } private int aheadcount(string s, list<string> list) { int count = 0 ; for ( int i= 0 ; i<list.size(); i++) { if ((s.length()<=list.get(i).length()) && (s.equals(list.get(i).substring( 0 , s.length())))) count ++; } return count; } public static void main(string[] args) { segmentation1 seg = new segmentation1(); seg.setdictionary(); string response1 = seg.leftmax(); system.out.println(response1); } } |
可以看到運行結(jié)果是:北京大學(xué)/生前/來/應(yīng)聘/
算法的核心就是從前往后搜索,然后找到最長的字典分詞。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對服務(wù)器之家的支持。
原文鏈接:http://blog.csdn.net/xiaoyeyopulei/article/details/25194021