单词转换就是:将一些缩写的单词转换为实际的文本。第一个文件保存的是转换的规则,而第二个文件保存的是要转换的文本。
假设单词转换的规则的文件如下:
brb be right back
k okay?
y why
r are
u you
pic picture
thk thanks!
l8r later
我们希望转换的文本为:
where r u
y dont you send me a picture
okay? thanks! later
则程序应该生成这样的输出:
where are you
why dont you send me a picture
okay? thanks! later
我们先定义word_transform函数,最重要的部分是调用buildMap和transform函数:
void word_transform(std::ifstream& map_file, std::ifstream& input) {
auto trans_map = buildMap(map_file);
std::string text;
while (getline(input, text)) {
std::istringstream stream(text);
std::string word;
bool firstword = true;
while (stream >> word) {
if (firstword)
firstword = false;
else
std::cout << " ";
std::cout << transform(word, trans_map);
}
std::cout << std::endl;
}
}
函数buildMap读入给定文件,建立起转换映射:
std::map<std::string, std::string> buildMap(std::ifstream& map_file) {
std::map<std::string, std::string> trans_map;
std::string key; // 要转换的单词
std::string value; // 替换后的内容
while (map_file >> key && getline(map_file, value)) {
if (value.size() > 1)
trans_map[key] = value;
else
throw std::runtime_error("no rule for" + key);
}
return trans_map;
}
而transform函数则将给定的字符串转换为对应文本:
const std::string& transform(const std::string& s, const std::map<std::string, std::string>& m) {
auto map_it = m.find(s);
if (map_it != m.cend())
return map_it->second;
else
return s;
}
我们主程序里调用:
int main(int argc, char* argv[])
{
// words transform
std::ifstream transRuleFile("transRule.txt");
std::ifstream wordsNdTransFile("wordsNeedTrans.txt");
word_transform(transRuleFile, wordsNdTransFile);
return 0;
}
输出为: