基於百度翻譯API開發屬於自己的翻譯工具

雲霏霏發表於2014-12-12

  你是否每天使用著網頁翻譯工具?你是否遇到過這種情況,上網過程中遇到一個很長的單詞但是又不能複製,要開兩個瀏覽器,一個開啟百度翻譯,照著另一個網頁輸入單詞?你安裝了各種翻譯軟體後,又刪除,只因忍受不了那每次彈出來的廣告?其實我們想要的就是簡單的翻譯一個單詞。今天就來使用百度翻譯開放API,做一個屬於自己的翻譯工具,只有簡單的翻譯功能,至於外觀自己根據自己的愛好,想做成什麼樣就做成什麼樣,終於可以任性一回了~~

下面先來看一下詞典效果:

 

 一、百度翻譯API簡介

 百度翻譯可以通過HTTP訪問,返回Json格式的翻譯結果,其使用方法如下:

GET請求方式:
http://openapi.baidu.com/public/2.0/bmt/translate?client_id=YourApiKey&q=today&from=auto&to=auto

其中有一個client_id,就是你的APP ID,可以參考下面連結這個你可以在百度開發者平臺申請。q=後面就是你要翻譯的內容,from後面跟的是原來的語種,to表示翻譯目標語種,auto表示自動識別。

如何獲取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

目前支援13中語種,如下圖:

 

 目前百度翻譯api共分為4檔,對普通開發者提供1000次/小時限制,支援擴容。每小時1000次,對於我們自己來說是夠用了。

 

當然我們主要使用的是英文和中文,也可以使用auto。既然可以通過GET的方式請求,我們先來在瀏覽器中測試一下,這裡我已經有ApiKey了,在瀏覽器中輸入如下Url:

這裡我們查詢單詞Hello,回車後可以看到瀏覽器輸出如下內容:

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

是Json格式的,我們先用工具來校檢一下,這裡我在http://www.bejson.com/進行校檢,得出結果如下:

這下看清楚了吧,from,to的意思就是從英語翻譯到中文,後面跟隨著翻譯結果,src後面的是原內容,dst後面的是翻譯結果。好了,清楚了資料格式,下面我們開始編寫自己的翻譯工具。

更多內容請參見百度翻譯官方API文件: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

 

 二、實現我們自己的詞典

   簡單的瞭解了百度翻譯API後,下面我們開始製作自己的翻譯軟體,這裡為了演示,介面做的簡單一點,新建WPF專案,名字就叫BaiduTrans吧,建完後,我們開啟MainWindow.xaml搭建簡單的頁面,如圖:

XAML程式碼如下:

<Window x:Class="BaiduTrans.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="查詞翻譯" Height="439" Width="525" WindowStartupLocation="CenterScreen" KeyDown="Window_KeyDown">
    <Grid>
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" FontSize="14" Name="textBlock1" Text="輸入單詞:" VerticalAlignment="Top" />
        <TextBox Height="94" HorizontalAlignment="Left" Margin="10,40,0,0" Name="txtWord" VerticalAlignment="Top" Width="487" />
        <Button Content="翻譯" FontSize="12" Height="26" HorizontalAlignment="Left" Margin="415,7,0,0" Name="button1" VerticalAlignment="Top" Width="82" Click="button1_Click" />
        <TextBox Height="242" HorizontalAlignment="Left" Margin="10,157,0,0" Name="txtResult" VerticalAlignment="Top" Width="487" />
    </Grid>
</Window>

 

參考剛剛我們得到的Json格式和百度官方的翻譯結果格式:

trans_result: [
{},
{},
{}
]

我們建立一個類,來存放反序列化後的翻譯結果,類目就叫TransObj,程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BaiduTrans
{
   public class TransObj
   {
      public string from { get; set; }
      public string to { get; set; }
      public List<TransResult> trans_result { get; set; }
   }

   public class TransResult
   {
      public string src { get; set; }
      public string dst { get; set; }
   }
}

至於Json的反序列化,我們使用Newtonsoft.Json,沒用過的可以參考Json序列化之.NET開源類庫Newtonsoft.Json的研究這篇文章。我們使用Nugget安裝Newtonsoft.Json,方法如下:

安裝完成後,我們雙擊翻譯按鈕,新增程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Newtonsoft.Json;
using System.Net;
using System.IO;

namespace BaiduTrans
{
   /// <summary>
   /// Interaction logic for MainWindow.xaml
   /// </summary>
   public partial class MainWindow : Window
   {
      public MainWindow()
      {
         InitializeComponent();
      }
      /// <summary>
      /// 1. + URL 中+號表示空格 %2B 
      ///2. 空格 URL中的空格可以用+號或者編碼 %20 
      ///3. / 分隔目錄和子目錄 %2F 
      ///4. ? 分隔實際的 URL 和引數 %3F 
      ///5. % 指定特殊字元 %25 
      ///6. # 表示書籤 %23 
      ///7. & URL 中指定的引數間的分隔符 %26 
      ///8. = URL 中指定引數的值 %3D
      /// </summary>
      /// <param name="sender"></param>
      /// <param name="e"></param>
      private void button1_Click(object sender, RoutedEventArgs e)
      {
         WebClient client = new WebClient();
         string txtInput = txtWord.Text;
         txtInput = txtInput.Replace(@"#","%23");
         string url = string.Format("http://openapi.baidu.com/public/2.0/bmt/translate?client_id=YourApiKey&q={0}&from=auto&to=auto", txtInput);
         var buffer = client.DownloadData(url);
         string result = Encoding.UTF8.GetString(buffer);
         StringReader sr = new StringReader(result);
         JsonTextReader jsonReader = new JsonTextReader(sr);
         JsonSerializer serializer = new JsonSerializer();
         var r = serializer.Deserialize<TransObj>(jsonReader);
         txtResult.Text = r.trans_result[0].dst;
      }

      private void Window_KeyDown(object sender, KeyEventArgs e)
      {
          if(e.Key == Key.Enter)
          {
              button1_Click(null, null);
          }
      }
   }
}

這裡請把client_id換成你們自己的,我們又新增了鍵盤事件,可以通過回車來進行查詢顯示查詢結果,至於一些特殊的符號處理,我這裡只處理了#號,如果大家需要,可以參考註釋裡面的進行處理,或者使用一些工具類。

下面我們來和網頁版的百度翻譯對比一下,我們的翻譯結果如下:

網頁版翻譯結果如下:

翻譯結果一樣,是吧~~ 到這裡,簡單的詞典功能就完成了,更多功能大家可以自由發揮~~

 

 作者:雲霏霏

QQ交流群:243633526

 部落格地址:http://www.cnblogs.com/yunfeifei/

 宣告:本部落格原創文字只代表本人工作中在某一時間內總結的觀點或結論,與本人所在單位沒有直接利益關係。非商業,未授權,貼子請以現狀保留,轉載時必須保留此段宣告,且在文章頁面明顯位置給出原文連線。

如果大家感覺我的博文對大家有幫助,請推薦支援一把,給我寫作的動力。

 

相關文章