Develop your own translation tools based on the Baidu translation API

Source: Internet
Author: User

Do you use Web translation tools every day? Have you encountered this situation, the Internet process encountered a long word but can not copy, to open two browsers, one open Baidu translation, according to another page input word? After you have installed a variety of translation software, and then delete, just because you can not bear the ads every time you play out? In fact, what we want is a simple translation of a single word. Today to use Baidu translation open API, to do a translation of their own tools, only a simple translation function, as to the appearance of their own hobbies, want to make what kind of, finally can be capricious a back ~ ~

Let's take a look at the dictionary effect:

first, Baidu translation API introduction

Baidu translation can be accessed via HTTP, return the translated results in JSON format, using the following methods:

GET Request mode: http: // Openapi.baidu.com/public/2.0/bmt/translate?client_id=yourapikey&q=today&from=auto&to=auto

There is a client_id, is your app ID, you can refer to the following link this you can apply on the Baidu developer platform. Q= behind is what you want to translate the content, from the back with the original language, to the translation target language, auto means automatic recognition.

how to get the API Key: http://developer.baidu.com/wiki/index.php?title=%E5%B8%AE%E5%8A%A9%E6%96%87%E6%A1%A3%E9%A6 %96%e9%a1%b5/%e7%bd%91%e7%ab%99%e6%8e%a5%e5%85%a5/%e5%85%a5%e9%97%a8%e6%8c%87%e5%8d%97

Currently supports 13 Chinese languages, such as:

at present, Baidu Translation API is divided into 4 files, the general developers to provide 1000 times/hour limit, to support the expansion. 1000 times per hour is enough for us.

Of course, we mainly use English and Chinese, we can also use Auto. Since we can request it by get, let's test it in the browser first, here I have Apikey, enter the following URL in the browser:

Here we query the word hello, enter after the browser output can see the following content:

{"from": "en", "to": "zh", "trans_result": [{"src": "Hello", "DST": "\u4f60\u597d"}]}

is the JSON format, we first use the tool to check the school, here I http://www.bejson.com/in the test, the results are as follows:

See clearly, from,to means from English translation to Chinese, followed by the translation results, src behind the original content, DST behind the translation results. Well, with the data format clear, let's start writing our own translation tools.

For more information, please refer to the official Baidu translation API document: http://developer.baidu.com/wiki/index.php?title=%E5%B8%AE%E5%8A%A9%E6%96%87%E6%A1%A3%E9%A6% 96%e9%a1%b5/%e7%99%be%e5%ba%a6%e7%bf%bb%e8%af%91/%e7%bf%bb%e8%af%91api

Ii. realization of our own dictionaries

Simple understanding of the Baidu translation API, the following we began to make their own translation software, here to demonstrate, the interface to do a simple point, the new WPF project, the name is called Baidutrans Bar, after the completion of the building, we open MainWindow.xaml to build a simple page,

The XAML code is as follows:

<Windowx:class= "Baidutrans.mainwindow"xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"Title= "Search word translation"Height= "439"Width= "525"windowstartuplocation= "Centerscreen"KeyDown= "Window_keydown">    <Grid>        <TextBlockHeight= "All"HorizontalAlignment= "Left"Margin= "12,12,0,0"FontSize= "+"Name= "TextBlock1"Text= "Enter Word:"VerticalAlignment= "Top" />        <TextBoxHeight= "94"HorizontalAlignment= "Left"Margin= "10,40,0,0"Name= "Txtword"VerticalAlignment= "Top"Width= "487" />        <ButtonContent= "Translation"FontSize= " a"Height= "+"HorizontalAlignment= "Left"Margin= "415,7,0,0"Name= "Button1"VerticalAlignment= "Top"Width= "the"Click= "Button1_Click" />        <TextBoxHeight= "242"HorizontalAlignment= "Left"Margin= "10,157,0,0"Name= "Txtresult"VerticalAlignment= "Top"Width= "487" />    </Grid></Window>

Refer to just the JSON format we got and the official Baidu translation result format:

Trans_result: [{},{},{}]

We create a class to hold the deserialized translation results, the class is called Transobj, the code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespacebaidutrans{ Public classTransobj { Public string  from{Get;Set; }  Public stringto {Get;Set; }  PublicList<transresult> Trans_result {Get;Set; } }    Public classTransresult { Public stringsrc {Get;Set; }  Public stringDST {Get;Set; } }}

As for JSON deserialization, we use Newtonsoft.json, which can be used to refer to the JSON serialization of the. NET open Source class library Newtonsoft.json this article. We use nugget to install Newtonsoft.json, as follows:

After the installation is complete, we double-click the Translate button and add the following code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Windows;usingSystem.Windows.Controls;usingSystem.Windows.Data;usingSystem.Windows.Documents;usingSystem.Windows.Input;usingSystem.Windows.Media;usingSystem.Windows.Media.Imaging;usingSystem.Windows.Navigation;usingSystem.Windows.Shapes;usingNewtonsoft.json;usingSystem.Net;usingSystem.IO;namespacebaidutrans{/// <summary>   ///Interaction logic for MainWindow.xaml/// </summary>    Public Partial classMainwindow:window { PublicMainWindow () {InitializeComponent (); }      /// <summary>      ///1. + URL + sign for space%2b///2. Spaces in the space URL can be used with the + number or code%20///3./separate directories and subdirectories%2f///4. Separate the actual URLs and parameters%3f///5.% Specify special characters%25///6. # means bookmark%23///7. The delimiter between the parameters specified in the & URL%26///8. = value of the specified parameter in the URL%3d/// </summary>      /// <param name= "Sender" ></param>      /// <param name= "E" ></param>      Private voidButton1_Click (Objectsender, RoutedEventArgs e) {WebClient Client=NewWebClient (); stringTxtinput =Txtword.text; Txtinput= Txtinput.replace (@"#","%23"); stringURL =string. Format ("Http://openapi.baidu.com/public/2.0/bmt/translate?client_id=yourapikey&q={0}&from=auto&to=auto ", Txtinput); varBuffer =client.         Downloaddata (URL); stringresult =Encoding.UTF8.GetString (buffer); StringReader SR=NewStringReader (Result); JsonTextReader Jsonreader=NewJsonTextReader (SR); Jsonserializer Serializer=NewJsonserializer (); varR = Serializer. Deserialize<transobj>(Jsonreader); Txtresult.text= r.trans_result[0].DST; }      Private voidWindow_keydown (Objectsender, KeyEventArgs e) {          if(E.key = =key.enter) {button1_click (NULL,NULL); }      }   }}

Here please replace the client_id with your own, we added a keyboard event, you can use the return to query display query results, as for some special symbolic processing, I only deal with the # number, if you need, you can refer to the comments inside the processing, or using some tool classes.

Below we come and the web version of Baidu Translation comparison, our translation results are as follows:

The results of the Web translation are as follows:

The result is the same, yes ~ ~ to here, the simple dictionary function is complete, more multifunctional people can play freely ~ ~

Cloud drizzling

QQ Exchange Group: 243633526

Blog Address: http://www.cnblogs.com/yunfeifei/

Disclaimer: The original text of this blog only represents my work in a certain time to summarize the views or conclusions, and my unit does not have a direct interest in the relationship. Non-commercial, unauthorized, post please keep the status quo, reprint must retain this paragraph statement, and in the article page obvious location to the original connection.

If you feel that my blog is helpful to everyone, please recommend supporting one, give me the motivation to write.

Develop your own translation tools based on the Baidu translation API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.