欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

庖丁分词的源码分析 (6) 我自己对庖丁分词的修改应用

程序员文章站 2022-07-13 16:51:15
...
1 我要满足一个需求,只返回在字典中的词。对于不在字典中的:庖丁默认的实现是两个字一分。我现在的这个需求相当于是覆盖这个对应的方法,让他不返回即可。我的实现就是覆盖了
CJKKnife的dissectIsolated方法,改成不做任何事情:


protected void dissectIsolated(Collector collector, Beef beef, int offset,
			int limit) {
		
	}


2 另外一个地方我们的需求是:不需要字典,全部都是两个字一分。不要字典其实我们自己实现起来也比较简单方便,但是感觉在庖丁的基础上改下可能也不错,然后我就这样做了。我仿照StandardTokenizer(这个是每个字一分,和我的需求很接近)写了个:TwoWordTokenizer

public final class TwoWordTokenizer extends Tokenizer {

	private int bufferIndex = 0;
	private int dataLen = 0;
	private final char[] buffer = new char[2];
	private char[] ioBuffer = new char[16];

	public TwoWordTokenizer(Reader in) {
		this.input = in;
	}

	public final Token next(Token reusableToken) throws IOException {
		int length = 0;
		while (true) {
			if (this.bufferIndex >= this.dataLen) {
				this.dataLen = this.input.read(this.ioBuffer);
				// 索引之前转为小写
				String inputString = new String(this.ioBuffer);
				inputString = inputString.toLowerCase();
				this.ioBuffer = inputString.toCharArray();

				this.bufferIndex = 0;
			}

			if (this.dataLen == -1) {
				return null;
			}

			char c = this.ioBuffer[(this.bufferIndex++)];

			if (Character.isLetter(c)) {
				this.buffer[(length++)] = c;
				if (length == 2) {
					this.bufferIndex -= 1;
					break;
				}
			}

		}
		
		if (length == 0) {
			return null;
		}

		return reusableToken.reinit(this.buffer, 0, length, 0, 0, "word");
	}
}


原理其实就是不断移动原始字符串的位置,去填充一个buffer,每次buffer填充两个字就next,next的时候buffer重新填充。会说这个说起来比较容易的功能,我当时就是看了半天,也许这个东西和c语言那些比较类似吧,看多了java代码证的是人容易变傻。