2013-06-22 87 views
1

我写了一个用于计算文本中特定单词频率的函数。该程序每次都返回零。我该如何改进它?计算文本中某个单词的频率数

while (fgets(sentence, sizeof sentence, cfPtr)) 
{ 
for(j=0;j<total4;j++) 
     { 
      frequency[j] = comparision(sentence,&w); 
      all_frequency+=frequency[j]; 
}} 
. 
. 
. 
int comparision(const char sentence[ ],char *w) 
{ 
    int length=0,count=0,l=0,i; 
    length= strlen(sentence); 
    l= strlen(w); 
    while(sentence[i]!= '\n') 
    if(strncmp(sentence,w,l)) 
     count++; 
    i++; 
    return count; 
    } 
+2

我很惊讶你的程序甚至回报。你使用了一个未初始化的'i',它在'while(sentence [i]!='\ n')中永远不会增加',因为由于缺少大括号,你的'i ++;'超出了循环范围。 –

+0

目前还不清楚w是什么,频率数组是如何初始化的,以及total4的含义。这不是一个很好的证明问题。 – catfood

+0

w是取自用户的单词。总数4是段落数量。 – user2500540

回答

2

我校对过你的代码,并对编码风格和变量名称进行了评论。 仍然是我留下的有条件的缺陷,这是因为没有遍历 句子。

这里是你的代码标记起来:

while(fgets(sentence, sizeof sentence, cfPtr)) { 
    for(j=0;j<total4;j++){ 
     frequency[j] = comparision(sentence,&w); 
     all_frequency+=frequency[j]; 
    } 

} 

// int comparision(const char sentence[ ],char *w) w is a poor variable name in this case. 

int comparison(const char sentence[ ], char *word) //word is a better name. 
{ 

    //int length=0,count=0,l=0,i; 

    //Each variable should get its own line. 
    //Also, i should be initialized and l is redundant. 
    //Here are properly initialized variables: 

    int length = 0; 
    int count = 0; 
    int i = 0; 

    //length= strlen(sentence); This is redundant, as you know that the line ends at '\n' 

    length = strlen(word); //l is replaced with length. 

    //while(sentence[i]!= '\n') 

    //The incrementor and the if statement should be stored inside of a block 
    //(Formal name for curley braces). 

    while(sentence[i] != '\n'){ 
     if(strncmp(sentence, word, length) == 0) //strncmp returns 0 if equal, so you  
      count++;        //should compare to 0 for equality 
     i++; 
    } 
    return count; 
} 
+0

此代码有一个基本问题:在每个while_loop计数器计数每个字符。我怎么解决这个问题? – user2500540

+0

这个程序有一个基本问题。在每一个while_loop中,计数器都会记录每个字符。我可以如何解决这个问题?我知道在这个程序中使用“strncmp”函数是不正确的。 – user2500540

+0

虽然使用strncmp对于这个问题是一个糟糕的选择,但它是完全有可能的。 (我会用strtok来抓住每个由空格分隔的单词)。通过使用指针算术,我们可以通过i的值来抵消句子,使您能够有效地在列表中搜索单词。因此,我们可以将strncmp的第一个参数改为(句子+ i)以这种方式解决问题。然而,这个解决方案并不是上下文敏感的,所以如果我们正在寻找“火”,并且我们找到“消防员”,那么它就会把这个数字视为文本中的火。 – jcccj1