【问题标题】:Getting Word Frequency From Vector In c++在 C++ 中从向量中获取词频
【发布时间】:2012-03-11 11:25:26
【问题描述】:

我已经用谷歌搜索了这个问题,但找不到适用于我的代码的答案,所以我写了这个来获取单词的频率唯一的问题是我得到了错误的单词出现次数,除了一个我认为是侥幸。另外我正在检查一个单词是否已经输入到向量中,所以我不会两次计算同一个单词。

fileSize = textFile.size();
vector<wordFrequency> words (fileSize);
int index = 0;
for(int i = 0; i <= fileSize - 1; i++)
{
    for(int j = 0; j < fileSize - 1; j++)
    {
        if(string::npos != textFile[i].find(textFile[j]) && words[i].Word != textFile[j])
        {
            words[j].Word = textFile[i];
            words[j].Times = index++;
        }
    }
    index = 0;
}

任何帮助将不胜感激。

【问题讨论】:

  • 出现次数是否超出预期?而textfile的find成员函数在你的程序中有什么作用???
  • @bhuwansahni 是的,我得到的是正确的。 find 是一个向量函数,用于查找匹配的字符串。
  • 那么 find 失败和成功的回报是什么??
  • @bhuwansahni 如果成功,它会添加单词和它发生的次数,如果失败,它什么也不做。
  • 你会在这里发布你的查找功能的代码吗??

标签: c++ vector struct words


【解决方案1】:

考虑改用std::map&lt;std::string,int&gt;。地图类将确保您没有任何重复。

【讨论】:

    【解决方案2】:

    使用关联容器:

    typedef std::unordered_map<std::string, unsigned> WordFrequencies;
    
    WordFrequencies count(std::vector<std::string> const& words) {
      WordFrequencies wf;
      for (std::string const& word: words) {
        wf[word] += 1;
      }
      return wf;
    }
    

    很难变得更简单......

    注意:如果您希望世界按字母顺序排序,您可以将 unordered_map 替换为 map,并且您可以编写自定义比较操作以不区分大小写。

    【讨论】:

      【解决方案3】:

      如果您不想使用地图容器,请尝试使用此代码。

          struct wordFreq{
          string word;
          int count;
          wordFreq(string str, int c):word(str),count(c){}
          };
      vector<wordFreq> words;
      
      int ffind(vector<wordFreq>::iterator i, vector<wordFreq>::iterator j, string s)
      {
          for(;i<j;i++){
              if((*i).word == s)
                  return 1;
          }
          return 0;
      }
      

      然后在文本文件向量中查找出现次数的代码是:

      for(int i=0; i< textfile.size();i++){
          if(ffind(words.begin(),words.end(),textfile[i]))    // Check whether word already checked for, if so move to the next one, i.e. avoid repetitions
              continue;
          words.push_back(wordFreq(textfile[i],1));          // Add the word to vector as it was not checked before and set its count to 1
          for(int j = i+1;j<textfile.size();j++){            // find possible duplicates of textfile[i]
              if(file[j] == (*(words.end()-1)).word)
                  (*(words.end()-1)).count++;
          }
      }
      

      【讨论】:

      • 需要进行一些调整,但现在可以使用了,感谢您的帮助。
      • 哎呀...这很尴尬!使用mapunordered_map 类要简单得多!
      猜你喜欢
      • 2016-09-17
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 2017-12-22
      相关资源
      最近更新 更多