中文分词--最少单词数

中文分词算法在前两篇文章中介绍了正向最大匹配算法和逆向最大匹配算法

本篇文章主要介绍最少单词数算法。顾名思义,就是最少的单词数。

算法思想是首先查找词典中最长的单词,匹配看是不是所要分词的字符串的子串,如果是则就是分词的词,迭代以上结果,每次都会在字符串中最长的单词分词,就可以得到最少的单词数

不多说了 直接上代码:

package com;

import java.util.ArrayList;
import java.util.List;

public class Segmentation2 {
	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("互利");
		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 String minWordsCount() {
		String response = "";
		String s = request;
		while(response.length()<request.length()) {
			for(int i=0; i<dictionary.size(); i++) {
				int start = isPart(s, dictionary.get(i));
				if(start != -1) {
					if(start != 0) {
						response += s.substring(0, start) + "/" + s.substring(start, dictionary.get(i).length()+start) + "/";
					} else {
						response += s.substring(start, dictionary.get(i).length()) + "/";
					}
					s = sub(s, dictionary.get(i), start);
				}
			}
		}
		return response;
	}
	
	private int isPart(String s1, String s2) {
		for(int i=0; i<=s1.length()-s2.length(); i++) {
			if(s1.substring(i, i+s2.length()).equals(s2)) return i;
		}
		return -1;
	}
	
	private String sub(String s1, String s2, int start) {
		String s = "";
		for(int i=start+s2.length(); i<s1.length(); i++) {
			s += s1.charAt(i);
		}
		return s;
	}
	
	public static void main(String[] args) {
		Segmentation2 seg = new Segmentation2();
		seg.setDictionary();
		String response1 = seg.leftMax();
		System.out.println(response1);
		String response2 = seg.minWordsCount();
		System.out.println(response2);
	}
}

运行结果可以看一下

独立自主/和平/等/互利/的/原则/
独立自主/和/平等互利/的/原则/

最少单词数效果还不错

点赞