针对一个文件 统计其中的单词和字符数 找出文件中出现次数最多的单词数 将文件中出现的单词按频率进行排序并输出

这篇博客展示了如何使用C++编程语言来统计一个文件中的单词和字符数,找出出现次数最多的单词,并将所有单词按照出现频率进行排序。通过引入map、vector、sort和Iterator等数据结构和算法,实现了从文件读取内容,计算单词频次,并将结果输出到新文件的功能。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <map>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include<algorithm>
#include<functional>
using namespace std;


int cmp(const pair<string,int> & x, const pair<string,int>& y)
{
    return x.second > y.second;
}
int main()
{
  map<string,int>::iterator it;
 map<string,int> ma;




 ifstream in("in.txt");//   读入的文件。
 ofstream out("result.txt");


 string str;
 string st;


  while( in>>st )
  {
   it=ma.find(st);
   if( it!=ma.end() )
    ++(*it).second;
   else
    ma[st]=1;
  }


 vector< p
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮您完成这个任务。这个任务可以分成两个步骤:首先,我们需要读取"data.txt"文件并将其内容转换为单词列表;然后,我们需要对单词列表进行统计出现频率最高的10个单词。 下面是完整的Python代码: ```python import re from collections import Counter def RedTxt(): with open('data.txt', 'r') as f: data = f.read() return data def GetWordList(text): # 将文本转换为单词列表 word_list = re.findall(r'\b\w+\b', text.lower()) return word_list def Top10Words(word_list): # 统计单词出现频率,并出现频率最高的10个单词 word_count = Counter(word_list) top_words = word_count.most_common(10) return [word[0] for word in top_words] # 读取"data.txt"文件 text = RedTxt() # 将文本转换为单词列表 word_list = GetWordList(text) # 出现频率最高的10个单词 top_words = Top10Words(word_list) # 输出结果 print("出现频率最高的10个单词:") for word in top_words: print(word) ``` 这个程序会将"data.txt"文件的内容读取到变量"text",然后将"text"转换为单词列表"word_list"。接下来,程序将统计"word_list"每个单词出现频率,并出现频率最高的10个单词。最后,程序将这10个单词存储在"top_words"列表,并在屏幕上输出这些单词。 请注意,这个程序的"GetWordList()"函数使用了正则表达式来将文本转换为单词列表。这个函数会将文本转换为小写,并忽略标点符号和其他非字母字符。如果您的文件包含其他非字母字符,您可能需要修改这个函数以确保程序能够正确地统计单词出现频率

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值