c++ - 用给定的字典构建 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;
}
我所写的只是转换单词。我怎样才能编写这段代码并使句子成为可能?
解决方案
干得好。
#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)
推荐阅读
- bash - 如何在 TCP 会话中运行脚本
- javascript - Puppeteer JS 从选择器生成 PDF
- excel - DynamicJasper:需要列仅跨越 Excel 中的一个单元格
- javascript - React 上下文状态属性未定义
- javascript - 触摸元素时如何显示X轴坐标(Javascript)?
- php - PHP mySQL INSERT 语句使用具有整数值的变量
- java - Akka Scheduler:仅在当前运行完成时运行下一个
- c++ - 使用 C++ 在 MongoDB 中查询日期字符串
- python - 字符串格式 .format 到变量
- java - Log4j2 打开的文件太多