1.百度语言翻译机
百度的工程师们是非常注重效率的,在长期的开发与测试过程中,他们逐渐创造了一套独特的缩略语。他们在平时的交谈、会议,甚至在各种技术文档中都会大量运用。
为了让新员工可以更快地适应百度的文化,更好地阅读公司的技术文档,人力资源部决定开发一套专用的翻译系统,把相关文档中的缩略语和专有名词翻译成日常语言。
输入要求:
输入数据包含三部分:
1. 第一行包含一个整数N(N<=10000),表示总共有多少个缩略语的词条;
2. 紧接着有N行的输入,每行包含两个字符串,以空格隔开。第一个字符串为缩略语(仅包含大写英文字符,长度不超过10字节),第二个字符串为日常语言(不包含空格,长度不超过255字节);
3. 从第N+2开始到输入结束为包含缩略语的相关文档(总长度不超过1000000个字节)。例:
6
PS 门户搜索部
NLP 自然语言处理
PM 产品市场部
HR 人力资源部
PMD 产品推广部
MD 市场发展部
百度的部门包括PS,PM,HR,PMD,MD等等,其中PS还包括NLP小组。
样例:in.txt
输出要求:
输出将缩略语转换成日常语言后的文档。(将缩略语转换成日常语言,其他字符保留原样)。例:
百度的部门包括门户搜索部,产品市场部,人力资源部,产品推广部,市场发展部等等,其中门户搜索部还包括自然语言处理小组。
样例:out.txt
我的解法:
-_-|||
做了下,很粗糙的算法。
#define DEBUG
#include <string>
#include <map>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
//#include <boost/algorithm/string/replace.hpp>
using namespace std;
using namespace boost;
struct Compare : public binary_function<string, string, bool>
{
bool operator()(const string& x, const string& y) const
{
if (x.size() != y.size())
{
return !(x.size() < y.size());
}
else
{
return x < y;
}
}
};
class Translate
{
typedef map<string, string, Compare> map_of_ab;
Translate(const Translate&);
void operator=(const Translate&);
public:
Translate(const string& filename);
void translate(const string& filename);
protected:
void parse();
void translate();
void parse_one_line(const string& str);
private:
ifstream file;
int num;
map_of_ab ab_list;
string source;
string target;
};
int main(void)
{
Translate tra("in.txt");
tra.translate("out.txt");
return 0;
}
Translate::Translate(const string& filename)
: file(filename.c_str())
{
}
void Translate::translate(const string& filename)
{
parse();
translate();
ofstream out(filename.c_str());
out << target;
}
void Translate::parse()
{
string buf;
getline(file, buf, '/n');
num = lexical_cast< int >(buf);
#ifdef DEBUG
cout << "num : " << num << endl;
#endif
for (int i = 0; i < num && !file.eof(); ++i)
{
getline(file, buf, '/n');
#ifdef DEBUG
// cout << "buf : " << buf << endl;
#endif
parse_one_line(buf);
}
file >> source;
#ifdef DEBUG
cout << "source : " << source << endl;
#endif
}
void Translate::translate()
{
target = source;
for (map_of_ab::const_iterator i = ab_list.begin(); i != ab_list.end(); ++i)
{
// replace(target, i.first, i.second);
string::size_type st;
do
{
st = target.find(i->first);
if (st != string::npos)
{
target.replace(st, i->first.size(), i->second);
}
}
while (st != string::npos);
#ifdef DEBUG
cout << "replace context with : " << i->first << endl;
#endif
}
}
void Translate::parse_one_line(const string& str)
{
string::size_type st;
st = str.find(' ');
ab_list[str.substr(0, st)] = str.substr(st + 1, str.size());
#ifdef DEBUG
cout << "key : |" << str.substr(0, st) << "| value : |" << ab_list[str.substr(0, st)] << "|" << endl;
#endif
}