网页查重-simhash算法的java实现

网页查重-simhash算法的java实现

在上一篇文章中,我们简单介绍了simhash算法,而在实际将它应用到网页查重中,我们首先需要分词算法将网页传来的数据流按照权重分开,但是由于对于中文和英文混杂的分词并不熟悉,我就十分偷懒的仅对英文进行分词,中文基本没管,简单的将所有的中文隔开,直接把所有含中文的字符串隔开,下面是java实现:
package test;
import java.math.BigInteger;
import java.util.*; 
import java.util.regex.*;

public class mysimhash {
	
	//通过正则将一些常用的在文本查重中无用的标签去掉
	private static String sp="=|\\.|。|,|\"|'|\\[|\\]|!|\\!|\\?|/|\n|\r| |||||| countString(){
		
		//先切割字符串,去掉一些分隔符
    	String[] st=this.tokens.split(sp);
    	String[] s=new String[max];
		int k=0;
		
		//去掉因为正则切割而造成的空格,并且将含中文的字符串分开
		for(int i=0;i hash_Data = new HashMap();
		for(int i=0;i hash_Data=countString();
    	Iterator iter = hash_Data.keySet().iterator();
    	while(iter.hasNext()){
    		String word=(String) iter.next();
    		
    		//计算hash值,并且按照64位的每一位进行计算,结果保存在v内
    		BigInteger t = this.hash(word);
    		for(int j=0;j= 0) {
                fingerprint = fingerprint.add(new BigInteger("1").shiftLeft(i));
                simHashBuffer.append("1");
            }else{
                simHashBuffer.append("0");
            }
        }
    	this.strSimHash = simHashBuffer.toString();
        return fingerprint;
    }
    
    //计算每个字符的hash值
    private BigInteger hash(String source) {
    	if (source == null || source.length() == 0) {
            return new BigInteger("0");
        } else {
            char[] sourceArray = source.toCharArray();
            BigInteger x = BigInteger.valueOf(((long) sourceArray[0]) << 7);
            BigInteger m = new BigInteger("1000003");
            BigInteger mask = new BigInteger("2").pow(this.hashbits).subtract(
                    new BigInteger("1"));
            for (char item : sourceArray) {
                BigInteger temp = BigInteger.valueOf((long) item);
                x = x.multiply(m).xor(temp).and(mask);
            }
            x = x.xor(new BigInteger(String.valueOf(source.length())));
            if (x.equals(new BigInteger("-1"))) {
                x = new BigInteger("-2");
            }
            return x;
        }
    }
    
    //求两字符串之间的距离
    public int getDistance(String str1, String str2) {  
        int distance;  
        if (str1.length() != str2.length()) {  
            distance = -1;  
        } else {  
            distance = 0;  
            for (int i = 0; i < str1.length(); i++) {  
                if (str1.charAt(i) != str2.charAt(i)) {  
                    distance++;  
                }  
            }  
        }  
        return distance;  
    }
}


参考资料: 局部敏感hash函数

你可能感兴趣的:(网页查重-simhash算法的java实现)