vba用的實在是不太好,謝謝高手幫忙改寫成vba能用的代碼
package testBuff;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class CosineSimilarAlgorithm {
public static double getSimilarity(String doc1, String doc2) {
if (doc1 != null && doc1.trim().length() > 0 && doc2 != null
&& doc2.trim().length() > 0) {
Map<Integer, int[]> AlgorithmMap = new HashMap<Integer, int[]>();
//將兩個字串中的中文字符以及出現的總數封裝到,AlgorithmMap中
for (int i = 0; i < doc1.length(); i++) {
char d1 = doc1.charAt(i);
if(isHanZi(d1)){
int charIndex = getGB2312Id(d1);
if(charIndex != -1){
int[] fq = AlgorithmMap.get(charIndex);
if(fq != null && fq.length == 2){
fq[0]++;
}else {
fq = new int[2];
fq[0] = 1;
fq[1] = 0;
AlgorithmMap.put(charIndex, fq);
}
}
}
}
for (int i = 0; i < doc2.length(); i++) {
char d2 = doc2.charAt(i);
if(isHanZi(d2)){
int charIndex = getGB2312Id(d2);
if(charIndex != -1){
int[] fq = AlgorithmMap.get(charIndex);
if(fq != null && fq.length == 2){
fq[1]++;
}else {
fq = new int[2];
fq[0] = 0;
fq[1] = 1;
AlgorithmMap.put(charIndex, fq);
}
}
}
}
Iterator<Integer> iterator = AlgorithmMap.keySet().iterator();
double sqdoc1 = 0;
double sqdoc2 = 0;
double denominator = 0;
while(iterator.hasNext()){
int[] c = AlgorithmMap.get(iterator.next());
denominator += c[0]*c[1];
sqdoc1 += c[0]*c[0];
sqdoc2 += c[1]*c[1];
}
return denominator / Math.sqrt(sqdoc1*sqdoc2);
} else {
throw new NullPointerException(
" the Document is null or have not cahrs!!");
}
}
public static boolean isHanZi(char ch) {
// 判斷是否漢字
return (ch >= 0x4E00 && ch <= 0x9FA5);
}
/**
* 根據輸入的Unicode字符,獲取它的GB2312編碼或者ascii編碼,
*
* @param ch
* 輸入的GB2312中文字符或者ASCII字符(128個)
* @return ch在GB2312中的位置,-1表示該字符不認識
*/
public static short getGB2312Id(char ch) {
try {
byte[] buffer = Character.toString(ch).getBytes("GB2312");
if (buffer.length != 2) {
// 正常情況下buffer應該是兩個位元組,否則說明ch不屬于GB2312編碼,故回傳'?',此時說明不認識該字符
return -1;
}
int b0 = (int) (buffer[0] & 0x0FF) - 161; // 編碼從A1開始,因此減去0xA1=161
int b1 = (int) (buffer[1] & 0x0FF) - 161; // 第一個字符和最后一個字符沒有漢字,因此每個區只收16*6-2=94個漢字
return (short) (b0 * 94 + b1);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return -1;
}
}
uj5u.com熱心網友回復:
樓主想要什么樣的功能?或許vb有更為簡潔的代碼........
uj5u.com熱心網友回復:
其實就是字頻統計,然后算相似度。自己什么都不做在線等的懶人,晾幾天再說。
說不定他自己就解決了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/96745.html
標籤:VBA
上一篇:關于陣列的一個問題,求解答
