#include "stdio.h"
#include "string.h"
#include "math.h"
#include "malloc.h" const long long Max_size = ;//输入字符串的最大长度,可以由单个词条和多个词条组成
const long long N = ;//输出与某个单词最接近的N个词
const long long Max_w = ;//单个词条的最大长度 int main(int argc,char **argv)
{
FILE *f;//读取的文件指针
char stemp[Max_size];//中间变量
char *bestw[N];//存储与某个词最接近N个词条
char ch;
float *M;//存储所有词条的距离相关信息
char *vocab;//存储所有词条的字符信息
/*
*file_name[Max_size];存放要读取内容的文件名;
*st[100][Max_size];//二维数组,中间变量
*dist:距离;len:长度;bestd[N]:存储与某个词最接近的N个词的距离
*vec[Max_size]:存储Max_size个词与某个指定词的距离
*words:词条的总数目;size:词条表示的维数;
*key[100],存储某个词条在总词条中的位置下标
*/
char file_name[Max_size],st[][Max_size];
float dist,len,bestd[N],vec[Max_size];
long long words,size,i,j,k,l,num,key[]; if(argc<)//打印程序所在路径
{
printf("Usage:./distance<FILE>\nwhere FILE contains word projections in the BINARY FORMAIN\n");
return ;
} strcpy(file_name,argv[]);//argv[1]中存放的文件名赋给file_name
f = fopen(file_name,"rb"); if(f == NULL)//文件打开失败
{
printf("Input file not found\n");
return -;
} fscanf(f,"lld",&words);//输入总词条数组
fscanf(f,"lld",&size);//输入用来表示每个词条的维数大小 vocab = (char *)malloc((long long)words * Max_w *sizeof(char)); //根据实际的维数分配存储块大小
for(i = ; i < N; i++)bestw[i] = (char *)malloc(Max_size * sizeof(char)); M = (float *)malloc((long long)words * (long long)size *sizeof(float));
if(M==NULL)//不能分配所需要大小的内存
{
printf("Cannot allocate memory:%lld MB %lld %lld\n",(long long )words *size*sizeof(float)//,words,size);
return -;
} for(j = ; j < words; j++)//words个词条每个词条坐标进行归一化
{
i = ;
while(true)
{
vocab[j*Max_w + i] = fgetc(f);
if(feof(f) || vocab[j * Max_w + i] == ' ')break;
if((i <Max_w)&&(vocab[j * Max_w + i] !='\n'))i++;
}
vocab[j * Max_w + i] = ;
for(i = ;i < size ; i++ ) fread(&M[j * size + i],sizeof(float),,f);
len = ;
for(i = ; i < size ; i++ ) len += M[j * size + i]*M[j * size + i];
len = sqrt(len);
for(i = ; i < size ; i++ ) M[j * size + i] = M[j * size + i] / len; //坐标归一化
}
fclose(f); while(true)
{
for(i = ; i < N ; i++ )
{
bestd[i] = ;//N个词条距离初始为0
bestw[i][] = ;//初始化
} printf("Entor word or sentence(EXIT to break:)"); i = ;
while(true)//键盘读入单个词条或多个词条 ;当字符数组超过Max_size -1 或者遇到回车符结束
{
stemp[i] = fgetc(stdin);
if((stemp[i] == '\n')||(i >=Max_size -))
{
stemp[i] = ;
break;
}
}
if(!strcmp(stemp,"EXIT"))break;//如果输入的是"EXIT",则退出 num = ;//用来统计键盘输入词条的数目
j = ;
k = ;
while(true)
{
st[num][j++] = stemp[k++];
st[num][j] = ;
if(stemp[k] ==)break;//读完结束
if(stemp[k++] == ' ')//遇到空格 词条数目+1
{
num++;//词条数目+1
j = ;
}
} num++;//词条的总数目 //找出每个词条 最接近的N个词条
for(i = ; i < num ; i++)
{
for(j = ; j < words ;j++)if(!strcmp(&vocab[j * Max_w],st[j]))break;//在总词条中找到这个词条,获得这个词条在总词条中的位置
if(j == words) j = -;//这个词条不存在
key[i] = j;
printf("\nWord:%s Position in vocabulary: %lld\n",st[i],key[i]); if(j == -)//这个词条不在这个词汇表中
{
printf("Out of dictionary word!\n");
break;//终止循环
}
} if(j==-)continue;//继续执行 printf("\n Word Cosine distance\n");
printf("------------------------------------------------------------------------\n"); for(i = ; i < size ; i++ ) vec[i] = ;//距离初始化为0
for(j = ; j < num ; j++ ) //遍历每个词,如果输入多个词向量vec[i]是各个词向量的累加和
{
if(key[j] == -)continue;
for(i = ; i < size ; i++ ) vec[i] += M[i + key[j]*size];
} len = ;
for(i = ; i< size ; i++) len +=vec[i] * vec[i];
len = sqrt(len); for(i = ; i < size ; i++) vec[i] = vec[i] / len;//将vec归一化,当只输入一个词时,不起作用 for(i = ; i < N ; i++)
{
bestd[i] = -;
bestw[i][] = ;
} //由于查询词和词汇表都做了归一化,所以余弦相似度等价于向量的内积,内机越大越相似
for(k = ; k < words ; k++)//遍历词汇表
{
i = ;
for(j = ; j < num ; j++)//i的作用;如果遍历词和查询词相同,则跳过此词
{
if(key[j] == k) i =;
}
if(i == ) continue;
dist = ; for(i = ; i < N ; i++ )
{
dist += vec[i] * M[k * size + i] ;
} for(i = ; i < N ; i++ )
{
if(dist > bestd[i])
{
for(j = N- ; j > i ; j--)
{
bestd[j] = bestd[j - ];
strcpy(bestw[j],bestw[j-]);
}
bestd[j] = dist;
strcpy(bestw[i] , &vocab[k * Max_size]);
break;
}
}
}
for(i = ; i < N ; i++ )printf("%50s\t\t%f\n",bestw[i],bestd[i]);
}
return ;
}

distance.c的更多相关文章

  1. [LeetCode] Total Hamming Distance 全部汉明距离

    The Hamming distance between two integers is the number of positions at which the corresponding bits ...

  2. [LeetCode] Hamming Distance 汉明距离

    The Hamming distance between two integers is the number of positions at which the corresponding bits ...

  3. [LeetCode] Rearrange String k Distance Apart 按距离为k隔离重排字符串

    Given a non-empty string str and an integer k, rearrange the string such that the same characters ar ...

  4. [LeetCode] Shortest Distance from All Buildings 建筑物的最短距离

    You want to build a house on an empty land which reaches all buildings in the shortest amount of dis ...

  5. [LeetCode] Shortest Word Distance III 最短单词距离之三

    This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as ...

  6. [LeetCode] Shortest Word Distance II 最短单词距离之二

    This is a follow up of Shortest Word Distance. The only difference is now you are given the list of ...

  7. [LeetCode] Shortest Word Distance 最短单词距离

    Given a list of words and two words word1 and word2, return the shortest distance between these two ...

  8. [LeetCode] One Edit Distance 一个编辑距离

    Given two strings S and T, determine if they are both one edit distance apart. 这道题是之前那道Edit Distance ...

  9. [LeetCode] Edit Distance 编辑距离

    Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2 ...

  10. C#实现Levenshtein distance最小编辑距离算法

    Levenshtein distance,中文名为最小编辑距离,其目的是找出两个字符串之间需要改动多少个字符后变成一致.该算法使用了动态规划的算法策略,该问题具备最优子结构,最小编辑距离包含子最小编辑 ...

随机推荐

  1. UI事件之load

    load事件属于CSS3规范中的UI事件,load事件处理程序在页面元素和资源(html/script/link/img等)全部加载完成后在window上触发,或在img元素加载完成后再img元素上触 ...

  2. hibernate:XXX is not mapped

    hibernate:XXX is not mapped  检查项目中是否将hbm.xml引入

  3. linux网络编程:使用单进程实现多客户端通信

    服务端: //回射服务器 //避免僵尸进程 #include "unistd.h" #include "sys/types.h" #include " ...

  4. 理解ThreadLocal(一)

    早在JDK 1.2的版本中就提供java.lang.ThreadLocal,ThreadLocal为解决多线程程序的并发问题提供了一种新的思路.使用这个工具类可以很简洁地编写出优美的多线程程序. Th ...

  5. eclipse 常用的一些设置

    1.行长度设置 http://blog.csdn.net/janronehoo/article/details/10047937 2.字体 windows -> preference -> ...

  6. cdoj 491 Tricks in Bits

    //无脑爆居然能过!!!!! 解:其实正解也是暴力,但是可以证明在n>6时答案一定为零. 第一步:对于任意两个数他们的二进制数要么有一半+的位是相同的,要么有一半+的位是不同的,于是首先使用与运 ...

  7. linux之模拟简单登录的脚本

    脚本如下: 运行结果:

  8. Binary Tree Level Order Traversal - leetcode - java

    Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...

  9. Create local metadata resource of yum

    Today, I need install an oracle software for a machine whose os is Linux. As we all know, installing ...

  10. 关于jqueryUI里的拖拽排序

    主要参考http://jsfiddle.net/KyleMit/Geupm/2/  (这个站需要FQ才能看到效果) 其实是jqueryUI官方购物车拖拽添加例子的增强版,就是在拖拽的时候增加了排序 这 ...