说明:
鉴于linux环境下没有像有道词典一样好用的自动取词翻译的软件,所以决定自己写一个,方便看文档的时候,随时翻译。
程序基于Python 完成。环境fedora20.
准备阶段:
需要安装三个程序,需要用xclip命令获得取词后获得的文本内容。用xlib库获取鼠标取词后完成后的瞬间动作。用pynotify用来气泡弹出翻译结果。
yum install xclipyum install python-xlibyum install python-notify
关于Xlib的相关信息见:http://blog.csdn.net/celte/article/details/28240829
程序代码:
#!/usr/bin/env python#-*- coding: utf-8 -*-import osimport sysfrom Xlib import X,XK,displayfrom Xlib.ext import recordfrom Xlib.protocol import rqimport urllib2import jsonimport pynotifyrecord_dpy=display.Display()# Create a recording context; we only want key and mouse eventsctx = record_dpy.record_create_context(0,[record.AllClients],[{'core_requests': (0, 0),'core_replies': (0, 0),'ext_requests': (0, 0, 0, 0),'ext_replies': (0, 0, 0, 0),'delivered_events': (0, 0),'device_events': (X.KeyPress, X.MotionNotify),'errors': (0, 0),'client_started': False,'client_died': False,}])pre_word="" #上次翻译的词语appkey="Your AppKey" #百度翻译申请的appKeydef viewTranslate():global pre_wordglobal appkeyurl="http://openapi.baidu.com/public/2.0/bmt/translate?client_id=%s&q=%s&from=auto&to=auto" % (appkey,pre_word)result=urllib2.urlopen(url).read()json_result=json.loads(result)pynotify.init("AutoTranslate")try:error_msg=json_result["error_msg"]query=json_result["query"]bubble=pynotify.Notification('"'+query+'"的翻译出错',error_msg)bubble.show()except:trans_result=json_result["trans_result"]src=trans_result[0]["src"]dst=trans_result[0]["dst"]bubble=pynotify.Notification('"'+src+'"的翻译结果',dst)bubble.show()def record_callback(reply):global pre_wordif reply.category != record.FromServer:returnif reply.client_swapped:#print "* received swapped protocol data, cowardly ignored"returnif not len(reply.data) or ord(reply.data[0]) < 2:# not an eventreturndata = reply.datawhile len(data):event, data = rq.EventField(None).parse_binary_value(data, record_dpy.display, None, None)if event.type == X.ButtonRelease:pipe = os.popen("xclip -o")text = pipe.readline()pipe.readlines() #清空管道剩余部分pipe.close()text=text.strip('\r\n\x00').lower().strip()if pre_word != text and text!="":pre_word=textviewTranslate() def gettext():os.system("xclip -f /dev/null") #清空剪切板record_dpy.record_enable_context(ctx,record_callback) record_dpy.record_free_context(ctx) def main():gettext() if __name__=='__main__': main()
感悟了不同的人生。凌晨,随着滑轮接触地面,