首页 > 解决方案 > 用给定的字典构建 C++ 翻译器?

问题描述

我正在尝试构建一个简单的翻译器,它可以根据给定的字典翻译句子。假设我们有两个字符串

string ENG[] = {"black","coffee", "want","yesterday"};
string SPA[] = {"negro", "café", "quiero", ayer"};

如果用户给出“我想要一杯黑咖啡”。结果应该是“我?quiro a?negro cafe”。这意味着对于字典字符串中没有翻译的单词,旁边应该有问号。

#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {

  string input string ENG[] = {"black", "coffee", "want", "yesterday"};
  string SPA[] = {"negro", "café", "quiero", "ayer"};

  cout << "Enter a word";
  cin >> input;

  for (int i = 0; i < 10; ++i) {
    if (ENG[i] == input) {
      cout << "You entered " << SPA[i] << endl;
    }
  }
  return 0;
}

我所写的只是转换单词。我怎样才能编写这段代码并使句子成为可能?

标签: c++stringword

解决方案


干得好。

#include <iostream>
#include <string>
#include <vector>

using namespace std;

vector <string> split_sentence(const string& arg)
{

    vector <string> ret;

    auto it = arg.begin();
    while (it != arg.end()) {

        string tmp;

        while (it != arg.end() && *it == ' ') ++it;
        while (it != arg.end() && *it != ' ')
            tmp += *it++;

        if (tmp.size())
            ret.push_back(tmp);
    }

    return ret;
}

int main(int argc, char *argv[])
{
    string input = "I want a black     coffee .";

    string ENG[4] = {"black","coffee", "want","yesterday"};
    string SPA[4] = {"negro", "café", "quiero", "ayer"};

    cout << "Enter sentence\n";
    /*
        cin >> input;
    */

    for (auto& str: split_sentence(input)) {

        bool found = false;

        for (int j=0; j<4 && !found; ++j) {

            if (ENG[j] == str) {
                cout << SPA[j] << " ";
                found = true;
            }
        }

        if (!found)
            cout << str << "? ";
    }

    cout << endl;
}

输出:

Enter sentence
I? quiero a? negro café .?

用空格分割句子,然后从 dict 中找到合适的单词。如果您是 dict,big enough您需要使用一些类似树的数据结构来提高速度或排序和散列。

编辑:

Trie will be faster for this. For each query you 
can get the appropriate word in O(m), m = length of
query(English word)

推荐阅读