这个是从网上看被人的代码然后自己修改的,工作原理是,鼠标选中单个单词或者一句话,再按下快捷键,就会出现翻译结果,非常方便,还可以发出声音,需要安装
mplayer

链接: http://pan.baidu.com/s/1kVAAgTp

ubuntu16.04翻译软件ubuntu16.04翻译软件

文件youdao_client.py

#!/usr/bin/env python


import urllib, urllib2
import os, sys
import re, time
import logging
import tempfile
import commands
import json
import subprocess
import requests

def json_encode(j):
    return json.dumps(j, indent=4)
def json_decode(j):
    return json.loads(j)

def system(cmd, log=True):
    subprocess.Popen(cmd, shell=True)


def query(word):
    session = requests.Session()
    url = 'http://fanyi.youdao.com/openapi.do?keyfrom=tinxing&key=1312427901&type=data&doctype=json&version=1.1&q=%s'%(word)
    #response = urllib2.urlopen(url,None)
    #data=response.read()
    r=session.get(url)
    return json_decode(r.text)

#this is much simper, 3ks mplayer
def pronounce(word):
    url = 'http://dict.youdao.com/dictvoice?audio=%s'%word
    cmd = 'nohup mplayer "%s" >/dev/null 2>&1 '%(url,)
    system(cmd)

def main(words):
    query(words)
    pronounce(words)
    pass

if __name__ == "__main__":
    p = subprocess.Popen('xclip -out', shell=True, stdout=subprocess.PIPE)
    out, err = p.communicate()
    resWord=""
    for line in out.splitlines():
        resWord+=line
    main(resWord)
    exit(0)

文件dict.py

#!/usr/bin/python
#coding: utf-8
#author : ning
#date   : 2013-03-08 21:16:14
import subprocess
import os
import re
import time
import fcntl
import logging

import pygtk
pygtk.require('2.0')
import gtk
import gobject
import webkit
import webbrowser
import youdao_client

VERSION = "0.1.0"
PWD = os.path.dirname(os.path.realpath(__file__))
LOGO = PWD + '/icon.png'

HOME = os.getenv("HOME") + '/.youdao-dict/'
COMMONWORDS_PATH = HOME + '/common_words.txt'
LOG_PATH = HOME + '/dict.log'
LOCK_PATH = HOME +  '/.lock'

if not os.path.exists(HOME):
    os.mkdir(HOME)
if not os.path.exists(COMMONWORDS_PATH):
    file(COMMONWORDS_PATH, 'w').close()

WHITELIST = set( [s.strip() for s in file(COMMONWORDS_PATH).readlines()])

logging.basicConfig(filename=LOG_PATH, level=logging.DEBUG)

class Dict:
    def __init__(self):
        self.mouse_in = False
        self.popuptime = 0
        self.last_selection = ''

        self.window = None
        self.view = None

        self.init_widgets()

    def init_widgets(self):
        '''
        window->vbox->eventbox->view
        '''
        self.window = gtk.Window(gtk.WINDOW_POPUP)
        self.window.set_title("youdao-dict-for-ubuntu")
        self.window.set_border_width(3)
        self.window.connect("destroy", lambda w: gtk.main_quit())
        self.window.resize(360, 200)

        vbox = gtk.VBox(False, 0)
        vbox.show()

        eventbox = gtk.EventBox()
        eventbox.connect('enter-notify-event', self._on_mouse_enter)
        eventbox.connect('leave-notify-event', self._on_mouse_leave)
        gobject.timeout_add(300, self._on_timer, eventbox)
        eventbox.show()

        self.view = webkit.WebView()
        self.view.show()


        #add one by one
        self.window.add(vbox)
        vbox.pack_start(eventbox) # means add
        eventbox.add(self.view)


    def _on_timer(self, widget):
        if self.window.get_property('visible') and not self.mouse_in:
            x, y = self.window.get_position()
            px, py, mods = self.window.get_screen().get_root_window().get_pointer()
            if (px-x)*(px-x) + (py-y)*(py-y) > 500:  # distance > 20 in x, 20 in y
                self.window.hide();
                exit(0)
            if(time.time() - self.popuptime > 5):   # popup for some seconds
                self.window.hide();
                exit(0)
        else:
            if(time.time() - self.popuptime > 5):   # popup for some seconds
                self.window.hide();
                exit(0)
        return True


    def query_word(self, word):
        js = youdao_client.query(word)
        youdao_client.pronounce(word)
        x, y, mods = self.window.get_screen().get_root_window().get_pointer()
        self.window.move(x+15, y+10)
        self.window.present()
        explains=''
        translation=''
        web =''
        phonetic=''
        if js.has_key('translation'):
            translation = '<br/>'.join(js['translation'])
        if js.has_key('basic'):
             if 'phonetic' in js['basic']:
                 phonetic = js['basic']['phonetic']
             if 'explains' in js['basic']:
                 explains = '<br/>'.join(js['basic']['explains'])
        if js.has_key('web'):
            web = '<br/>'.join( ['<a href="http://dict.youdao.com/search?le=eng&q=%s">%s</a>: %s'%(i['key'],i['key'], ' '.join(i['value'])) for i in js['web'][:3] ] )
        html = '''
<style>
.add_to_wordbook {
    background:  no-repeat;
    vertical-align: middle;
    overflow: hidden;
    display: inline-block;
    vertical-align: top;
    width: 20px;
    padding-top: 20px;
    height: 0;
    margin-left: .5em;
}
</style>
        <h2>
        %(translation)s
        <span style="color: #0B6121; font-size: 13px">< %(phonetic)s > </span>
        </h2>
        <span style="color: #A0A0A0; font-size: 14px"> </span>
        <b>基本翻译:</b>
        <p> %(explains)s </p>
        <span style="color: #A0A0A0; font-size: 14px"> </span>
        <b>网络释意:</b>
        <p> %(web)s </p>
        ''' % locals()
        self.view.load_html_string(html, '')
        self.view.reload()
        self.popuptime = time.time()

    def ignore(self, word):
        if len(word)<=3:
            return True
        if word in WHITELIST:
            return True
        return False

    def _on_mouse_enter(self, wid, event):
        self.popuptime = time.time()
        self.mouse_in = True

    def _on_mouse_leave(self, *args):
        self.mouse_in = False
        self.window.hide()



def main(words):
    d=Dict()
    d.query_word(words)
    gtk.main()

resWord=""
if __name__ == "__main__":
    f=open(LOCK_PATH, 'w')
    try:
        fcntl.flock(f.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
    except:
        print 'a process is already running!!!'
        exit(0)
    p = subprocess.Popen('xclip -out', shell=True, stdout=subprocess.PIPE)
    out, err = p.communicate()
    for line in out.splitlines():
        resWord+=line
    if not resWord.strip():
        exit(0)
    else:
        main(resWord)
把上面两段代码分别复制到youdao_client.py和dict.py两个文件中,放在固定的目录下面,然后设置系统systemsettings/keyboard/shortcut/customshortcut点加号新建一个自定义快捷键,command写上/path/dict.py然后保存,用鼠标选择一段英文,按下快捷键,是不是效果就出来了?

另外基于api的翻译会在未来停止服务,同时我申请了新api的id做了试验,也用web版的有道做了一个新的

文件dict.py  //这个是包含了新api和基于web的翻译和显示

#!/usr/bin/python
#coding: utf-8
#author : ning
#date   : 2013-03-08 21:16:14
import subprocess
import os
import re
import time
import fcntl
import logging

import pygtk
pygtk.require('2.0')
import gtk
import gobject
import webkit
import webbrowser
import youdao_client

VERSION = "0.1.0"
PWD = os.path.dirname(os.path.realpath(__file__))
LOGO = PWD + '/icon.png'

HOME = os.getenv("HOME") + '/.youdao-dict/'
COMMONWORDS_PATH = HOME + '/common_words.txt'
LOG_PATH = HOME + '/dict.log'
LOCK_PATH = HOME +  '/.lock'

if not os.path.exists(HOME):
    os.mkdir(HOME)
if not os.path.exists(COMMONWORDS_PATH):
    file(COMMONWORDS_PATH, 'w').close()

WHITELIST = set( [s.strip() for s in file(COMMONWORDS_PATH).readlines()])

logging.basicConfig(filename=LOG_PATH, level=logging.DEBUG)

class Dict:
    def __init__(self):
        self.mouse_in = False
        self.popuptime = 0
        self.last_selection = ''

        self.window = None
        self.view = None

        self.init_widgets()

    def init_widgets(self):
        '''
        window->vbox->eventbox->view
        '''
        self.window = gtk.Window(gtk.WINDOW_POPUP)
        self.window.set_title("youdao-dict-for-ubuntu")
        self.window.set_border_width(3)
        self.window.connect("destroy", lambda w: gtk.main_quit())
        self.window.resize(360, 200)

        vbox = gtk.VBox(False, 0)
        vbox.show()

        eventbox = gtk.EventBox()
        eventbox.connect('enter-notify-event', self._on_mouse_enter)
        eventbox.connect('leave-notify-event', self._on_mouse_leave)
        gobject.timeout_add(300, self._on_timer, eventbox)
        eventbox.show()

        self.view = webkit.WebView()
        self.view.show()


        #add one by one
        self.window.add(vbox)
        vbox.pack_start(eventbox) # means add
        eventbox.add(self.view)


    def _on_timer(self, widget):
        if self.window.get_property('visible') and not self.mouse_in:
            x, y = self.window.get_position()
            px, py, mods = self.window.get_screen().get_root_window().get_pointer()
            if (px-x)*(px-x) + (py-y)*(py-y) > 800:  # distance > 20 in x, 20 in y
                self.window.hide();
                exit(0)
            if(time.time() - self.popuptime > 5):   # popup for some seconds
                self.window.hide();
                exit(0)
        else:
            if self.mouse_in:
                if(time.time() - self.popuptime > 25):
                    exit(0)
            else :
                if (time.time() - self.popuptime > 5):   # popup for some seconds
                   self.window.hide();
                   exit(0)
        if(time.time() - self.popuptime>40) :
            exit(0)
        return True


    def query_word(self, word):
        self.popuptime = time.time()
        js = youdao_client.query(word)
        x, y, mods = self.window.get_screen().get_root_window().get_pointer()
        self.window.move(x+15, y+10)
        self.window.present()
        explains=''
        translation=''
        web =''
        phonetic=''
        if js.has_key('translation'):
            translation = '<br/>'.join(js['translation'])
        if js.has_key('basic'):
             if 'phonetic' in js['basic']:
                 phonetic = js['basic']['phonetic']
             if 'explains' in js['basic']:
                 explains = '<br/>'.join(js['basic']['explains'])
        if js.has_key('web'):
            web = '<br/>'.join( ['<a href="http://dict.youdao.com/search?le=eng&q=%s">%s</a>: %s'%(i['key'],i['key'], ' '.join(i['value'])) for i in js['web'][:3] ] )
        html = '''
<style>
.add_to_wordbook {
    background:  no-repeat;
    vertical-align: middle;
    overflow: hidden;
    display: inline-block;
    vertical-align: top;
    width: 20px;
    padding-top: 20px;
    height: 0;
    margin-left: .5em;
}
</style>
        <h2>
        %(translation)s
        <span style="color: #0B6121; font-size: 13px">< %(phonetic)s > </span>
        </h2>
        <span style="color: #A0A0A0; font-size: 14px"> </span>
        <b>基本翻译:</b>
        <p> %(explains)s </p>
        <span style="color: #A0A0A0; font-size: 14px"> </span>
        <b>网络释意:</b>
        <p> %(web)s </p>
        ''' % locals()
        self.view.load_html_string(html, '')
        self.view.reload()
        self.popuptime = time.time()
        youdao_client.pronounce(word)

    def ignore(self, word):
        if len(word)<=3:
            return True
        if word in WHITELIST:
            return True
        return False

    def _on_mouse_enter(self, wid, event):
        self.popuptime = time.time()
        self.mouse_in = True

    def _on_mouse_leave(self, *args):
        self.mouse_in = False
        self.window.hide()
        exit(0)
    def query_word_web(self, word):
        explains=''
        translation=''
        web =''
        phonetic=''
        soup = youdao_client.query_web(word)
        youdao_client.pronounce(word)
        prons = soup.find_all('span', {'class': 'pronounce'})
        if prons:
            for pron in prons:
                phonetic+= pron.text.replace(' ', '').replace('\n', '')
        content = \
                soup.find('div', {'class': 'results-content', 'id': 'results-contents'})
        if content:
            container =content.find('div', {'class': 'trans-container'})#.ul.find_all('li')
            containerLable=container.find('ul')
            if containerLable:
                definitions = containerLable.find_all('li')
                if definitions:
                    translation = word
                    if definitions:
                        for define in definitions:
                            text = define.text
                            explains += text + '<br/>'
                    word_groups = content.find('div', {'class': 'pr-container more-collapse'})
                    word_groups = word_groups.find_all('p', {'class': r'wordGroup'})
                    if word_groups:
                        for group in word_groups:
                            if len(group['class']) != 1:
                                break
                            phras = group.span.a.text.strip()
                            text = group.text.replace(phras, '')
                            text = re.sub(r'\s+', ' ', text)
                            text = text.strip().split(';')
                            if text:
                                web += '<br/><a href="http://dict.youdao.com/search?le=eng&q=%s">%s</a>' % (
                                phras, phras) + ':'
                                for i, t in enumerate(text[1:]):
                                    web += (t.strip() + (';' if i != len(text) - 2 else ''))
            if not containerLable:
                containerLable=container.find('span')
                if  containerLable:
                    definitions = containerLable.find_all('li')
                    if definitions:
                        translation = word
                        if definitions:
                            for define in definitions:
                                text = define.text
                                explains += text + '<br/>'
                        word_groups = content.find('div', {'class': 'pr-container more-collapse'})
                        word_groups = word_groups.find_all('p', {'class': r'wordGroup'})
                        if word_groups:
                            for group in word_groups:
                                if len(group['class']) != 1:
                                    break
                                phras = group.span.a.text.strip()
                                text = group.text.replace(phras, '')
                                text = re.sub(r'\s+', ' ', text)
                                text = text.strip().split(';')
                                if text:
                                    web += '<br/><a href="http://dict.youdao.com/search?le=eng&q=%s">%s</a>' % (
                                    phras, phras) + ':'
                                    for i, t in enumerate(text[1:]):
                                        web += (t.strip() + (';' if i != len(text) - 2 else ''))
            if not containerLable:
                containerLable=container.find_all('p')
                if containerLable:
                    index=0
                    for splitWord in containerLable:
                        if index%2==0:
                            pass
                        else:
                            translation+=splitWord.text
                        index=index+1
        else:
            exit(0)
        x, y, mods = self.window.get_screen().get_root_window().get_pointer()
        self.window.move(x+15, y+10)
        self.window.present()
        html = '''
<style>
.add_to_wordbook {
    background:  no-repeat;
    vertical-align: middle;
    overflow: hidden;
    display: inline-block;
    vertical-align: top;
    width: 20px;
    padding-top: 20px;
    height: 0;
    margin-left: .5em;
}
</style>
        <h2>
        %(translation)s
        <span style="color: #0B6121; font-size: 13px">< %(phonetic)s > </span>
        </h2>
        <span style="color: #A0A0A0; font-size: 14px"> </span>
        <b>基本翻译:</b>
        <p> %(explains)s </p>
        <span style="color: #A0A0A0; font-size: 14px"> </span>
        <b>网络释意:</b>
        <p>%(web)s</p>
        ''' % locals()
        self.view.load_html_string(html, '')
        self.view.reload()
        self.popuptime = time.time()
def main(words):
    d=Dict()
    d.query_word_web(words)
    #d.query_word(words)
    gtk.main()

resWord=""
if __name__ == "__main__":
    f=open(LOCK_PATH, 'w')
    try:
        fcntl.flock(f.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB)
    except:
        print 'a process is already running!!!'
        exit(0)
    p = subprocess.Popen('xclip -out', shell=True, stdout=subprocess.PIPE)
    out, err = p.communicate()
    for line in out.splitlines():
        resWord+=line
    if not resWord.strip():
        exit(0)
    if resWord=="": exit(0)
    else:
        try:
           main(resWord)
        except:exit(0)
文件youdao_client.py 这个文件是基于web和新的api的翻译

#!/usr/bin/env python


import urllib, urllib2
import os, sys
import re, time
import logging
import tempfile
import commands
import json
import subprocess
import requests
import hashlib
from bs4 import BeautifulSoup
def json_encode(j):
    return json.dumps(j, indent=4)
def json_decode(j):
    return json.loads(j)

def system(cmd, log=True):
    subprocess.Popen(cmd, shell=True)

def escape(s):
    def _print(x):
        x = x.group()
        code, x = x[0:2], x[2:]
        if code != '\\x':
            return x
        return ('%'+str(x)).upper()

    s = repr(s)
    return re.sub(r'\\x[0-9a-fA-F]{2}', _print, s)
def query_web(word):
    url="http://dict.youdao.com/search?q=%s&keyfrom=new-fanyi.smartResult"%word
    url=url.encode('utf-8')
    resultData=requests.get(url)
    html_doc = resultData.content
    soup = BeautifulSoup(html_doc, "html.parser")
    return soup

def query(word):
    appKey = "到有道云申请的key"
    md5Str=appKey+word+"2"+"有道申请的**"
    md5Str=hashlib.md5(md5Str.encode("utf-8")).hexdigest()
    url = 'http://openapi.youdao.com/api?q=%s&from=auto&to=auto&appKey=%s&salt=2&sign=%s'%(word,appKey,md5Str)
    url=url.encode('utf-8')
    r=requests.get(url)
    return json_decode(r.text)
#this is much simper, 3ks mplayer
def pronounce(word):
    url = 'http://dict.youdao.com/dictvoice?audio=%s'%word
    cmd = 'nohup mplayer "%s" >/dev/null 2>&1 '%(url,)
    system(cmd)

def main(words):
    query(words)
    pronounce(words)
    pass

if __name__ == "__main__":
    p = subprocess.Popen('xclip -out', shell=True, stdout=subprocess.PIPE)
    out, err = p.communicate()
    resWord=""
    for line in out.splitlines():
        resWord+=line
    main(resWord)
    exit(0)

使用api或者web的区分办法是在dict.py的main里面,如果使用

d.query_word_web(words)就是使用web获得翻译结果,如果使用
d.query_word(words)就是使用api翻译,使用api必须要到有道云申请appkey和签名,然后复制到程序对应的地方就可以翻译了。

相关文章: