中文分詞--逆向最大匹配

  1. 上一篇文章中介紹了正向最大匹配,可以看到有時候效果不是很好,這裏在介紹一種逆向最大匹配的算法。詞典和匹配的字符串都和上一篇文章相同</span>  

只是本算法是從後到前搜索字符串,然後找到最長的匹配結果輸出。上代碼

[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1.   
[java] view plain copy
 print?在CODE上查看代碼片派生到我的代碼片
  1. <pre code_snippet_id="331438" snippet_file_name="blog_20140507_2_819878" name="code" class="java">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.     private boolean isIn(String s, List<String> list) {  
  23.         for(int i=0; i<list.size(); i++) {  
  24.             if(s.equals(list.get(i))) return true;  
  25.         }  
  26.         return false;  
  27.     }  
  28.       
  29.     public String rightMax() {  
  30.         String response = "";  
  31.         String s = "";  
  32.         for(int i=request.length()-1; i>=0; i--) {  
  33.             s = request.charAt(i) + s;  
  34.             if(isIn(s, dictionary) && tailCount(s, dictionary)==1) {  
  35.                 response = (s + "/") + response;  
  36.                 s = "";  
  37.             } else if(tailCount(s, dictionary) > 0) {  
  38.                   
  39.             } else {  
  40.                 response = (s + "/") + response;  
  41.                 s = "";  
  42.             }  
  43.         }  
  44.         return response;  
  45.     }  
  46.       
  47.     private int tailCount(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(list.get(i).length()-s.length(), list.get(i).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 response2 = seg.rightMax();  
  59.         System.out.println(response2);  
  60.     }  
  61. }  
  62. </pre><br>  
  63. <br>  
  64. <pre></pre>  
  65. <br>  
  66. <p>可以看到運行結果是:北京/大學生/前來/應聘/</p>  
  67. <p>分詞效果很好</p>  
  68. <p><br>  
  69. </p>  
  70.      
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章