C++實現統計文本文件中的詞頻(支持自己載入文件)

-直接代碼

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int MAXN = 100;

class wordtype{ //單詞類
public:
	string word; //單詞
	int count; //數量
};

int getwords(wordtype *words) //單詞搜索模塊函數
{
	string filename;
	cout<<"請輸入文件名(txt):"<<endl;
	cin>>filename;
	ifstream in(filename.c_str());//打開文件
	if(!in) {
		cout<<"文件打開錯誤!"<<endl;
		return 1;
	}
	
	int n=0, m;
	string word;
	while(in) {
		in>>word; //讀單詞
		if(!in) { //文件結尾時退出循環
			break;
		}
		bool flag = false;
		for(m=0;m<n;m++)
		{
			if(word==words[m].word) { //已存在該單詞
				words[m].count++; //原有單詞計數加1 
				flag=true;
				break;
			}
		}
		
		if(!flag) { //發現新單詞
			words[m].count=1; //新單詞計數爲1
			words[m].word=word; //保存新單詞
			n++; //總單詞計數加1
		}
	}
	in.close(); //關閉文件
	
	return n; //返回單詞個數
}


int main() //主函數 
{
	string s;
	wordtype words[MAXN] = {"",0}; //單詞對象變量定義與初始化
	int n=getwords(words); //調用獲取單詞的函數
	
	cout<<"英文單詞統計結果如下:"<<endl;
	for(int m=0;m<n;m++)
	{
	cout<<words[m].word<<':'<<words[m].count<<endl;
	}
	cout<<"搜索出共"<<n<<"個單詞。"<<endl;
	
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章