开发环境:Ubuntu12.04 + GCC4.7
一、 有道翻译API
API 地址:http://fanyi.youdao.com/openapi
这里我选择了数据调用接口key的申请,填入相关信息,然后系统会提供API Key和Keyfrom字段给你,同时会发送一份包含这2项的邮件到你所填写的邮箱。
有道翻译API的数据接口如下:
http://fanyi.youdao.com/openapi.do keyfrom=&key=&type=data&doctype=&version=1.1&q=要翻译的文本
版本:1.1,请求方式:get,编码方式:utf-8
主要功能:中英互译,同时获得有道翻译结果和有道词典结果(可能没有)
参数说明:
type - 返回结果的类型,固定为data
doctype - 返回结果的数据格式,xml或json或jsonp
version - 版本,当前最新版本为1.1
q - 要翻译的文本,不能超过200个字符,需要使用utf-8编码
errorCode:
0 - 正常
20 - 要翻译的文本过长
30 - 无法进行有效的翻译
40 - 不支持的语言类型
50 - 无效的key
二、 Curl和JsonCpp的安装
2.1 Curl的安装
Curl工程主页:http://curl.haxx.se/, 目前最新版本是curl-7.34.0,
下载解压后进入curl-7.34.0目录,用如下命令安装:
1 cd $CURL_HOME
2 mkdir build
3 cd build
4 cmake ..
5 make
2.2 JsonCpp的安装
JsonCpp工程主页:http://jsoncpp.sourceforge.net/,目前的最新版本是jsoncpp-src-0.5.0,下载解压后进入jsoncpp-src-0.5.0,使用Scons进行安装,Scons是一个
Python编译
系统,没有安装的童鞋需要先安装Scons,如下:
1 sudo apt-get install scons
Scons安装好之后就可以编译JsonCpp了,使用如下命令:
1 scons platform=linux-gcc
好了,JsonCpp已经成功安装了,为了后面程序编译链接过程中方便,我在JsonCpp路径下的libs文件夹中设置了一个软连接,如下:
1 ln -s libjson_linux-gcc-4.7_libmt.a libjson_linux-gcc.a
三、 在线翻译工具
直接贴代码:
复制代码
1 /*
2 Filename: translate.cc
3 Author: BerlinSun
4 */
5 #include
6 #include "curl/curl.h"
7 #include "json/json.h"
8
9 using namespace std;
10
11 void usage()
12 {
13 cout << "Usage: translate word_you_want_to_translate" << endl;
14 }
15
16 int writer(char *data, size_t size, size_t nmemb, string *writerData)
17 {
18 if (writerData == NULL)
19 return 0;
20 int len = size*nmemb;
21 writerData->append(data, len);
22 return len;
23 }
24
25 int main(int argc, char *argv[])
26 {
27 if(argc < 2)
28 {
29 usage();
30 exit(0);
31 }
32 string buffer;
33 string translate_url = "http://fanyi.youdao.com/openapi.do keyfrom=xxxxxx&key=xxxxxx&type=data&doctype=json&version=1.1&q=";
34 translate_url += argv[1];
35 CURL * curl;
36 CURLcode res;
37 curl = curl_easy_init();
38 if (curl)
39 {
40 curl_easy_setopt(curl, CURLOPT_URL, translate_url.c_str());
41 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer);
42 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
43 res = curl_easy_perform(curl);
44 curl_easy_cleanup(curl);
45 }
46 if (buffer.empty())
47 {
48 cout << "The server return NULL!" << endl;
49 exit(0);
50 }
51
52 Json::Value root;
53 Json::Reader reader;
54 bool parsingSuccessful = reader.parse(buffer, root);
55
56 if (!parsingSuccessful)
57 {
58 cout << "Failed to parse the data!" << endl;
59 exit(0);
60 }
61
62 const Json::Value basic = root["basic"];
63 const Json::Value phonetic = basic["phonetic"];
64 const Json::Value explains = basic["explains"];
65 cout << "Provided by Youdao dictionary!" << endl;
66 cout << "-----------------------------" << endl;
67 cout << argv[1] << "\t英[" << phonetic.asString() << "]" << endl;
68
69 for(int i = 0; i < explains.size(); ++i)
70 cout << explains[i].asString() << endl;
71
72 return 0;
73 }
复制代码
PS:代码中红色加粗的部分就是你所申请到的key和keyfrom字段。
CMake文件如下: