2013-06-22 84 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