linux 鼠标取词,Linux桌面鼠标取词自动翻译

说明: 鉴于linux环境下没有像有道词典一样好用的自动取词翻译的软件,所以决定自己写一个,方便看文档的时候,随时翻译。 程序基于Python 完成。环境fedora20. 准备阶段: 需要安装三个程序,需要用xclip命令获得取词后获得的文本内容。用xlib库获取鼠标取

说明:

鉴于linux环境下没有像有道词典一样好用的自动取词翻译的软件,所以决定自己写一个,方便看文档的时候,随时翻译。

程序基于Python 完成。环境fedora20.

准备阶段:

需要安装三个程序,需要用xclip命令获得取词后获得的文本内容。用xlib库获取鼠标取词后完成后的瞬间动作。用pynotify用来气泡弹出翻译结果。

yum install xclip

yum install python-xlib

yum install python-notify

关于Xlib的相关信息见:http://blog.csdn.net/celte/article/details/28240829

程序代码:

#!/usr/bin/env python

#-*- coding: utf-8 -*-

import os

import sys

from Xlib import X,XK,display

from Xlib.ext import record

from Xlib.protocol import rq

import urllib2

import json

import pynotify

record_dpy=display.Display()

# Create a recording context; we only want key and mouse events

ctx = 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" #百度翻译申请的appKey

def viewTranslate():

global pre_word

global appkey

url="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_word

if reply.category != record.FromServer:

return

if reply.client_swapped:

#print "* received swapped protocol data, cowardly ignored"

return

if not len(reply.data) or ord(reply.data[0]) < 2:# not an event

return

data = reply.data

while 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=text

viewTranslate()

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值