zoukankan      html  css  js  c++  java
  • 中文分词——正向最大匹配法

    中文分词应用非常广泛,网上也有非常多开源项目。

    我在这里主要讲一下中文分词里面算法的简单实现,废话不多说了,如今先上代码

    package com;
    
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    public class Segmentation1 {
    	private List<String> dictionary = new ArrayList<String>();
    	private String request = "北京大学生前来应聘";
    	
    	public void setDictionary() {
    		dictionary.add("北京");
    		dictionary.add("北京大学");
    		dictionary.add("大学");
    		dictionary.add("大学生");
    		dictionary.add("生前");
    		dictionary.add("前来");
    		dictionary.add("应聘");
    	}
    	
    	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);
    	}
    }

    能够看到执行结果是:北京大学/生前/来/应聘/

    算法的核心就是从前往后搜索,然后找到最长的字典分词。

  • 相关阅读:
    python安装mysqldb
    2月8日
    python反射机制
    python备忘
    Nginx+Tomcat动静分离及Nginx优化
    yum挂在iso文件yum源配置
    升级apache
    解决编译apache出现的问题:configure: error: APR not found . Please read the documentation
    学习网站总结
    面试题:登录页面测试
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5095980.html
Copyright © 2011-2022 走看看