当前位置:   article > 正文

topK问题——统计一篇很长的英文文章中频次出现最高的10个单词_一本英文书,怎么统计出现频率最高的10个单词

一本英文书,怎么统计出现频率最高的10个单词

 

上篇讲述了topK问题N个数中最大的前K个数,本篇则讲述统计一篇很长的英文文章中频次出现最高的10个单词。

 

例题2统计一篇很长的英文文章中频次出现最高的10个单词。

思路:  分治法 + hash + 小根堆

(1) 定义一个关联容器hash_map<string,int>,用于统计英文文章中每个单词出现的次数;定义一个vector<hash_map<string,int>::iterator>,用于存储小根堆K;

(2) 将英文文章中的前K个单词先填满topK堆;

(3) 调整topK堆为小根堆结构;

(4) 通过遍历将后面的单次出现的次数与堆顶单词出现的次数(此时堆顶单词出现的次数最小)比较,大于堆顶元素就入堆,并下调堆结构。

(5) 遍历结束,则小根堆中的单词即英文文章中频次出现最高的10个单词。

代码如下:

  1. // topK问题 统计一篇英文文章中出现频次最高的10个单词 分治法 + hash + 小根堆
  2. #include<iostream>
  3. #include<fstream>
  4. #include<vector>
  5. #include<string>
  6. #include<hash_map>
  7. #include<algorithm>
  8. using namespace std;
  9. // 调整堆
  10. void adjustDown(vector<hash_map<string, int>::iterator> &topK, int i, int k)
  11. {
  12. int min = i;
  13. int child = 2 * min + 1;
  14. while (min < k / 2)
  15. {
  16. if (child + 1 < k && topK[child]->second > topK[child + 1]->second)
  17. child++;
  18. if (child<k && topK[min]->second>topK[child]->second)
  19. {
  20. swap(topK[min], topK[child]);
  21. min = child;
  22. child = 2 * min + 1;
  23. }
  24. else
  25. break;
  26. }
  27. }
  28. // 建小根堆
  29. void buildHeap(vector<hash_map<string, int>::iterator> &topK, int k)
  30. {
  31. for (int i = k / 2 - 1; i >= 0; i--)
  32. adjustDown(topK, i, k);
  33. }
  34. // 获取文章中出现频次最高的前k个单词
  35. void getTopK(hash_map<string, int> &essay, vector<hash_map<string, int>::iterator> &topK, int k)
  36. {
  37. auto it = essay.begin();
  38. for (int i = 0; i < k; i++)
  39. {
  40. topK[i] = it;
  41. it++;
  42. }
  43. buildHeap(topK, k);
  44. for (; it != essay.end(); it++)
  45. {
  46. if (it->second>topK[0]->second)
  47. {
  48. topK[0] = it;
  49. adjustDown(topK, 0, k);
  50. }
  51. }
  52. // 输出出现频次最高的前k个单词及其频次
  53. for (int i = 0; i < k; i++)
  54. cout << topK[i]->first << " " << topK[i]->second << endl;
  55. }
  56. int main()
  57. {
  58. // 读入英文文章
  59. ifstream in("data.txt");
  60. string word;
  61. hash_map<string, int> essay; // hash_map统计每个单词出现频次
  62. while (in >> word)
  63. {
  64. essay[word]++;
  65. }
  66. int k;
  67. while (cin >> k)
  68. {
  69. vector<hash_map<string, int>::iterator> topK(k, essay.begin());
  70. getTopK(essay, topK, k);
  71. }
  72. return 0;
  73. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/864133
推荐阅读
相关标签
  

闽ICP备14008679号