这是深信服的一道笔试题,即要求扫描一文本文件,将出现频率最高的单词过滤。所以自己也写了个代码。本代码没有做“单词测试”,即没有测试是否一个字符串是一个单词。
题目没有要求针对相同频率单词的处理情况,所以我没有针对这个做处理,有兴趣的朋友可以自立要求。
#include <fstream>
#include <iostream>
#include <map>
using namespace std;
void clr_frc(string srcf, string desf)
{
// 创建 单词->频率 计数表
map<string, int> cnt;
// ifstream要求原始C字符串,所以要将string转成c字符串作参数
ifstream fin(srcf.c_str());
string str;
// 累计单词数量
while (fin >> str) {
++cnt[str];
}
// 初始化最大频率单词频率数
int max = 0; // max frequant number
string rsstr; // result string
// 遍历计数表
for (map<string, int>::iterator iter=cnt.begin();
iter!=cnt.end(); ++iter) {
if (iter->second > max) {
max = iter->second;
rsstr = iter->first;
}
}
// 输入文件因为读取到eof结束标记所以状态(state)...
// 被作了标记eof状态,所以要将状态清空还原正常状态
fin.clear();
// 将文件指针指回文件首
fin.seekg(0, ios::beg);
// 创建输出文件流
ofstream fout(desf.c_str());
bool first = true; // write the first word to file
// 输出除频率最高单词外的其它单词
while (fin >> str) {
if (str != rsstr) {
if (first) // it doesn't need space before the first word
first = false;
else fout << " ";
fout << str;
}
}
}
int main(int argv, char** args)
{
clr_frc("file.txt", "modify.txt");
getchar();
return 0;
}