中文分詞——正向最大匹配法

中文分詞應用很廣泛,網上也有很多開源項目。我在這裏主要講一下中文分詞裏面算法的簡單實現,廢話不多說了,現在先上代碼

[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. package com;  
  2.   
  3.   
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7.   
  8. public class Segmentation1 {  
  9.     private List<String> dictionary = new ArrayList<String>();  
  10.     private String request = "北京大學生前來應聘";  
  11.       
  12.     public void setDictionary() {  
  13.         dictionary.add("北京");  
  14.         dictionary.add("北京大學");  
  15.         dictionary.add("大學");  
  16.         dictionary.add("大學生");  
  17.         dictionary.add("生前");  
  18.         dictionary.add("前來");  
  19.         dictionary.add("應聘");  
  20.     }  
  21.       
  22.     public String leftMax() {  
  23.         String response = "";  
  24.         String s = "";  
  25.         for(int i=0; i<request.length(); i++) {  
  26.             s += request.charAt(i);  
  27.             if(isIn(s, dictionary) && aheadCount(s, dictionary)==1) {  
  28.                 response += (s + "/");  
  29.                 s = "";  
  30.             } else if(aheadCount(s, dictionary) > 0) {  
  31.                   
  32.             } else {  
  33.                 response += (s + "/");  
  34.                 s = "";  
  35.             }  
  36.         }  
  37.         return response;  
  38.     }  
  39.       
  40.     private boolean isIn(String s, List<String> list) {  
  41.         for(int i=0; i<list.size(); i++) {  
  42.             if(s.equals(list.get(i))) return true;  
  43.         }  
  44.         return false;  
  45.     }  
  46.       
  47.     private int aheadCount(String s, List<String> list) {  
  48.         int count = 0;  
  49.         for(int i=0; i<list.size(); i++) {  
  50.             if((s.length()<=list.get(i).length()) && (s.equals(list.get(i).substring(0, s.length())))) count ++;  
  51.         }  
  52.         return count;  
  53.     }  
  54.       
  55.     public static void main(String[] args) {  
  56.         Segmentation1 seg = new Segmentation1();  
  57.         seg.setDictionary();  
  58.         String response1 = seg.leftMax();  
  59.         System.out.println(response1);  
  60.     }  
  61. }  

可以看到運行結果是:北京大學/生前/來/應聘/

算法的核心就是從前往後搜索,然後找到最長的字典分詞。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章