C++ 读取文件

本文介绍了一个使用C++实现的文本处理程序,该程序能够读取文本文件,并统计除去特定停用词之外的单词出现频率。通过遍历文件内容并利用标准库中的数据结构进行词频统计,最后输出每个有效单词及其出现次数。
#include <iostream>
#include <fstream>
#include <vector> 
#include <string>
#include <map>
using namespace std;

string trim(string s){
    if(s.empty())
        return s;
    s.erase(0,s.find_first_not_of(" "));
    s.erase(s.find_last_not_of(" ") + 1);
    return s;
}

void readTxt(string file){
	std:map<std::string, int> newMap;
    ifstream infile; 
    infile.open(file.data());   //将文件流对象与文件连接起来 
    char c;
    infile >> noskipws;         //不忽略空白字符,将其读取
    string stopword = " ,;?.!0123456789";
    string tmp = "";
    while (!infile.eof())
    {
		infile >> c;
		if(stopword.find(c) != string::npos){
			tmp = trim(tmp);
			if(tmp.length() == 0)
				continue; 
    		if(niuMap.count(tmp) > 0){
    			niuMap[tmp] += 1;
			}
			else{
				niuMap.insert(map<string, int>::value_type (tmp, 1));
			}
			tmp = "";
		}
    	else{
        	tmp += c;
        	
	    }
    }
    infile.close();             //关闭文件输入流 

    for(auto it = newMap.begin(); it != newMap.end(); ++it){
    	cout << it->first << ":" << it->second << endl;
	}

	
}

int main(){
	string a;
	cin >> a;
    readTxt(a);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值