【问题标题】:counting number of frequency of a word in a text [duplicate]计算文本中单词的频率数[重复]
【发布时间】:2013-06-22 04:03:03
【问题描述】:

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

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;
    }

【问题讨论】:

  • 我很惊讶你的程序竟然回来了。您使用了一个未初始化的i,它在您的while(sentence[i]!= '\n') 中永远不会增加,因为您的i++; 由于缺少花括号而超出了循环范围。
  • 也不清楚 w 是什么,频率数组是如何初始化的,也不清楚 total4 是什么。这不能很好地说明问题。
  • w 是取自用户的一个词。 total4 是段落数。
  • 通过编写更好的代码来改进它? ;) 这是一个家庭作业问题。这甚至应该在 SO 上吗?
  • 是的,这是我的家庭作业的平静。你能帮帮我吗?

标签: c++ string counting


【解决方案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)  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;
}

【讨论】:

  • 这段代码有一个基本问题:在每个 while_loop 中,计数器都会对每个字符进行计数。我该如何解决这个问题?
  • 这个程序有一个基本问题。在每个 while_loop 中,计数器都会计算每个字符。我该如何解决这个问题?我知道在这个程序中使用“strncmp”函数是不正确的。
  • 虽然使用 strncmp 对于这个问题来说是一个糟糕的选择,但很有可能。 (我会使用 strtok 来抓取由空格分隔的每个单词)。通过使用指针算法,我们可以将句子偏移 i 的值,让您可以有效地遍历列表搜索单词。因此,我们可以将 strncmp 的第一个参数更改为 (sentence + i) 来以这种方式解决问题。但是,此解决方案不是上下文相关的,因此如果我们正在寻找“火”并且我们找到“消防员”,它会将其视为文本中的火。
猜你喜欢
  • 2016-01-23
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多