/*********************************************************************************
* #######程序:单词转换程序#######
* 从规则文件中读取规则,从输入文件中输入数据
----------- ----------- ---------------
| | |k okay? | | |
|where r u | |y why | |where are you |
|y dont u --->>> |r are --->>> |why dont you |
|k thk | |u you | |okay? thanks! |
| | |thk thanks!| | |
----------- ----------- ---------------
* 实现过程: 1、void word_transform(ifstream &map_file, ifstream &input_file, ofstream &out_file)
管理整个过程,并将结果输出到文件
* 2、map<string, string> buildMap(ifstream &map_file)
读取转换规则文件并创建map;
* 3、const string & transform(const string &s, const map<string, string> &m)
接受一个string,如果存在转换规则,返回转换后的内容,否则返回原值;
**************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <map>
#include <vector>
using namespace std;
map<string, string> buildMap(ifstream &map_file)
{
map<string, string> trans_map;
string key,value;
while (map_file>>key,getline(map_file,value))
{
if (value.size() > 1)
trans_map[key] = value.substr(1);//此处如果改为:trans_map.insert({key, value.substr(1)});
//前者的key对应的值为输入的最后一个,后者第一个,
//这与使用下标和insert的方式不同有关。
else
throw runtime_error("no rule for " + key);
/*trans_map[key] = value.substr(1);*/
}
return trans_map;
}
const string & transform(const string &s, const map<string, string> &m)
{
auto map_it = m.find(s);//如果使用下标的方式,当关键字未在容器中时,会导致容器中新添加一个元素
if (map_it == m.cend())
{
return s;
}
else
return map_it->second;
}
void word_transform(ifstream &map_file, ifstream &input_file, ofstream &out_file)
{
auto trans_map = buildMap(map_file);
string line;
while (getline(input_file,line))
{
istringstream stream(line);
string word;
bool firstword = true;
while (stream>>word)
{
if (firstword)
firstword = false;
else
out_file << " ";
out_file << transform(word, trans_map);
}
out_file << endl;
}
}
int main(void)
{
ifstream map_file("D:\\f_map_file.txt");
ifstream input_file("D:\\f_input_file.txt");
ofstream out_file("D:\\f_out_file.txt");
if (!map_file || !input_file || !out_file)
{
cerr << "Can't open the file." << endl;
return -1;
}
word_transform(map_file, input_file, out_file);
return 0;
}
对应的txt内容:
f_map_file.txt:
k okay?
y why
r are
u you
thk thanks!
f_input_file.txt:
where r u
y dont u
k thk
输出结果f_out_file.txt:
where are you
why dont you
okay? thanks!