zoukankan      html  css  js  c++  java
  • 单词替换程序demo

    #include <fstream>
    #include <map>
    #include <string>
    #include <sstream>

    #include <iostream>

    using namespace std;

    map<string,string> buildMap(ifstream &map_file) {
     map<string, string> trans_map;
     string key;//要替换的单词
     string value;//替换后的内容
     //读取map_file文件,将单词存入key中,剩余要替换的内容存入value中
     while (map_file >> key&&getline(map_file, value)) {
      //检查是否有转换规则
      if (value.size() > 1) {
       trans_map[key] = value.substr(1);//跳过前导空格
      }
      else {
       throw runtime_error("no rule for " + key);
      }
     }
     return trans_map;
    }

    string transform(const string &word,const map<string,string> &m) {
     auto it = m.find(word);
     if (it!=m.cend()) {
      return it->second;
     }
     else {
      return word;
     }
    }


    void  WordConversion(ifstream &map_file, ifstream &input) {
     auto trans_map = buildMap(map_file);
     string text;//保存输入的每一行
     while (getline(input, text)) {
      //处理每一个单词
      istringstream stream(text);
      string word;
      bool isspace = true;//控制是否打印空格
      while (stream >> word) {
       if (isspace)
        isspace = false;
       else {
        cout << " ";
       }
       cout << transform(word, trans_map);
      }
      cout << endl;
     }
    }


    int main() {
     ifstream map_file("C:/Users/Administrator/Desktop/map_file.txt");
     ifstream input("C:/Users/Administrator/Desktop/input.txt");
     WordConversion(map_file, input);
     system("pause");

     return 0;
    }

    map_file.txt 文件

    brb be right back
    k okay?
    y why
    r are
    u you
    pic picture
    thk thanks!
    l8r later

    input.txt 文件

    where r u
    y dont u send me a pic
    k thk l8r

  • 相关阅读:
    我的20130220日 在北京 do{ Web Develop } while(!die)
    关于NVelocity模板引擎初学总结
    C# 23种设计模式汇总
    基于模型的设备故障检测
    图像去噪之光斑去除
    虹膜识别
    封闭曲线拟合
    基于故障树的系统可靠性分析
    图像识别之棋子识别
    时间序列的模式距离
  • 原文地址:https://www.cnblogs.com/codingtao/p/6026624.html
Copyright © 2011-2022 走看看