利用simhash计算文本相似度
摘自:http://www.programcreek.com/java-api-examples/index.php?source_dir=textmining-master/src/com/gta/simhash/SimHash.java
package com.gta.simhash;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s3 = "�������Ϻ���������죬���������������������Ͼ������ݣ����������ţ����ϣ��ൺ���人�����ݣ����ڣ��ɶ���������̫ԭ����ɳ�����֣�������֣�ݣ���������������³ľ�룬���ݣ��������Ϸʣ��ߺ�";
String s4 = "�������Ϻ���������죬���������������������Ͼ������ݣ����������ţ����ϣ��ൺ���人�����ݣ����ڣ��ɶ���������̫ԭ����ɳ�����֣�������֣�ݣ�����";
SimHash hash1 = new SimHash(s3, 64, 8);
SimHash hash2 = new SimHash(s4, 64, 8);
hash1.getResult(hash2);
}
}
package com.gta.simhash; import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
import java.util.ArrayList; import org.wltea.analyzer.lucene.IKAnalyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; public class SimHash {
private String tokens;
private int hashBits = 64;
private int distance = 5; public SimHash(String tokens)
{
this.tokens = tokens;
} public SimHash(String tokens, int hashBits, int distance)
{
this.tokens = tokens;
this.hashBits = hashBits;
this.distance = distance;
} public List<TermDict> tokenizer()
{
List<TermDict> terms = new ArrayList<TermDict>();
IKAnalyzer analyzer = new IKAnalyzer(true);
try {
TokenStream stream = analyzer.tokenStream("", this.tokens);
CharTermAttribute cta = stream.addAttribute(CharTermAttribute.class);
stream.reset();
int index = -1;
while (stream.incrementToken())
{
if ((index = isContain(cta.toString(), terms)) >= 0)
{
terms.get(index).setFreq(terms.get(index).getFreq()+1);
}
else
{
terms.add(new TermDict(cta.toString(), 1));
}
}
analyzer.close();
} catch (IOException e) {
e.printStackTrace();
}
return terms;
} public int isContain(String str, List<TermDict> terms)
{
for (TermDict td : terms)
{
if (str.equals(td.getTerm()))
{
return terms.indexOf(td);
}
}
return -1;
} public BigInteger simHash(List<TermDict> terms)
{
int []v = new int[hashBits];
for (TermDict td : terms)
{
String str = td.getTerm();
int weight = td.getFreq();
BigInteger bt = shiftHash(str);
for (int i = 0; i < hashBits; i++)
{
BigInteger bitmask = new BigInteger("1").shiftLeft(i);
if ( bt.and(bitmask).signum() != 0)
{
v[i] += weight;
}
else
{
v[i] -= weight;
}
}
} BigInteger fingerPrint = new BigInteger("0");
for (int i = 0; i < hashBits; i++)
{
if (v[i] >= 0)
{
fingerPrint = fingerPrint.add(new BigInteger("1").shiftLeft(i)); // update the correct fingerPrint
}
}
return fingerPrint;
} public BigInteger shiftHash(String str)
{
if (str == null || str.length() == 0)
{
return new BigInteger("0");
}
else
{
char[] sourceArray = str.toCharArray();
BigInteger x = BigInteger.valueOf((long) sourceArray[0] << 7);
BigInteger m = new BigInteger("131313");
for (char item : sourceArray)
{
x = x.multiply(m).add(BigInteger.valueOf((long)item));
}
BigInteger mask = new BigInteger("2").pow(hashBits).subtract(new BigInteger("1"));
boolean flag = true;
for (char item : sourceArray)
{
if (flag)
{
BigInteger tmp = BigInteger.valueOf((long)item << 3);
x = x.multiply(m).xor(tmp).and(mask);
}
else
{
BigInteger tmp = BigInteger.valueOf((long)item >> 3);
x = x.multiply(m).xor(tmp).and(mask);
}
flag = !flag;
} if (x.equals(new BigInteger("-1")))
{
x = new BigInteger("-2");
}
return x;
}
} public BigInteger getSimHash()
{
return simHash(tokenizer());
} public int getHammingDistance(SimHash hashData)
{
BigInteger m = new BigInteger("1").shiftLeft(hashBits).subtract(new BigInteger("1"));
System.out.println(getFingerPrint(getSimHash().toString(2)));
System.out.println(getFingerPrint(hashData.getSimHash().toString(2)));
BigInteger x = getSimHash().xor(hashData.getSimHash()).and(m);
int tot = 0;
while (x.signum() != 0)
{
tot += 1;
x = x.and(x.subtract(new BigInteger("1")));
}
System.out.println(tot);
return tot;
} public String getFingerPrint(String str)
{
int len = str.length();
for (int i = 0; i < hashBits; i++)
{
if (i >= len)
{
str = "0" + str;
}
}
return str;
} public void getResult(SimHash hashData)
{
if (getHammingDistance(hashData) <= distance)
{
System.out.println("match");
}
else
{
System.out.println("false");
}
} }
利用simhash计算文本相似度的更多相关文章
- 利用sklearn计算文本相似性
利用sklearn计算文本相似性,并将文本之间的相似度矩阵保存到文件当中.这里提取文本TF-IDF特征值进行文本的相似性计算. #!/usr/bin/python # -*- coding: utf- ...
- C#动态规划法计算文本相似度
C# 采用动态规划算法,计算两个字符串之间的相似程度. public static double CountTextSimilarity(string textX, string textY, boo ...
- DSSM算法-计算文本相似度
转载请注明出处: http://blog.csdn.net/u013074302/article/details/76422551 导语 在NLP领域,语义相似度的计算一直是个难题:搜索场景下quer ...
- Java根据余弦定理计算文本相似度
项目中需要算2个字符串的相似度,是根据余弦相似性算的,下面具体介绍一下: 余弦相似度计算 余弦相似度用向量空间中两个向量夹角的余弦值作为衡量两个个体间差异的大小.余弦值越接近1,就表明夹角越接近0度, ...
- NLP点滴——文本相似度
[TOC] 前言 在自然语言处理过程中,经常会涉及到如何度量两个文本之间的相似性,我们都知道文本是一种高维的语义空间,如何对其进行抽象分解,从而能够站在数学角度去量化其相似性.而有了文本之间相似性的度 ...
- 转:Python 文本挖掘:使用gensim进行文本相似度计算
Python使用gensim进行文本相似度计算 转于:http://rzcoding.blog.163.com/blog/static/2222810172013101895642665/ 在文本处理 ...
- 从0到1,了解NLP中的文本相似度
本文由云+社区发表 作者:netkiddy 导语 AI在2018年应该是互联网界最火的名词,没有之一.时间来到了9102年,也是项目相关,涉及到了一些AI写作相关的功能,为客户生成一些素材文章.但是, ...
- 【机器学习】使用gensim 的 doc2vec 实现文本相似度检测
环境 Python3, gensim,jieba,numpy ,pandas 原理:文章转成向量,然后在计算两个向量的余弦值. Gensim gensim是一个python的自然语言处理库,能够将文档 ...
- NLP文本相似度(TF-IDF)
本篇博文是数据挖掘部分的首篇,思路主要是先聊聊相似度的理论部分,下一篇是代码实战. 我们在比较事物时,往往会用到“不同”,“一样”,“相似”等词语,这些词语背后都涉及到一个动作——双方的比 ...
随机推荐
- Educational Codeforces Round 27 F. Guards In The Storehouse
F. Guards In The Storehouse time limit per test 1.5 seconds memory limit per test 512 megabytes inpu ...
- web应用的负载均衡、集群、高可用(HA)解决方案
看看别人的文章: 1.熟悉几个组件 1.1.apache —— 它是Apache软件基金会的一个开放源代码的跨平台的网页服务器,属于老牌的web服务器了,支持基于Ip或者域名的虚拟主机,支持代 ...
- ADC 分辨率和精度的区别(转载)
转自:http://hi.baidu.com/jnjypbpuhkbajmq/item/8a6b472ae86dcc69469962b7 分辨率和精度这两个,经常拿在一起说,才接触的时候经常混为一谈. ...
- 简单的积雪shader
// Upgrade NOTE: replaced '_World2Object' with 'unity_WorldToObject' Shader "Custom/CoverSnow&q ...
- Redis(Windows安装方法与Java调用实例 & 配置文件参数说明 & Java使用Redis所用Jar包 & Redis与Memcached区别 & redis-cli.exe命令及示例)
Windows下Redis的安装使用 0.前言 因为是初次使用,所以是在windows下进行安装和使用,参考了几篇博客,下面整理一下 1.安装Redis 官方网站:http://redis.io/ 官 ...
- windows中wamp环境composer使用中openssl问题解决
今天在windows下学习lavaral,使用composer update命令报如下错误: [Composer\Exception\NoSslException] The openssl exten ...
- iOS开发之获取系统相册ALAssetLibrary
注:当你选择看这篇博客时想必你的应用还支持iOS8一下系统,如果你的应用要求最低版本大于iOS8,建议使用PhotoKit框架,效率更高 ALAssetsLibrary包含,ALAssetsLibra ...
- iframe自动全屏
<iframe src="weixin.php" id="adlistpage" name="adlistpage" framebor ...
- CSS 布局实例系列(四)如何实现容器中每一行的子容器数量随着浏览器宽度的变化而变化?
Hello,小朋友们,还记得我是谁吗?对了,我就是~超威~好啦,言归正传,今天的布局实例是: 实现一个浮动布局,红色容器中每一行的蓝色容器数量随着浏览器宽度的变化而变化,就如下图: 肯定有人心里犯嘀咕 ...
- python 安装anaconda, numpy, pandas, matplotlib 等
如果没安装anaconda,则这样安装这些库: pip install numpy pip install pandas pip install matplotlib sudo apt-get ins ...