您的位置:首页 > 编程语言 > Python开发

(六)高级功能调研

2014-08-24 19:09 337 查看
本周主要对高级功能的实现进行了调研,还未实现的高级功能是模糊查询和划词翻译,在之前提案的基础上进行了进一步调研,探究这两种功能实现的原理以及可实现性。

一、实现原理

1、对模糊查询来说需要一个字典库,然后使用通配符进行查询,将包含关键字的单词(包括头部,中间和尾部)提取出来,返回结果集,

2、划词翻译在windows和linux下都有现有的软件,比如windows下的有道、灵格斯,linux下的openyoudao,windows下实现的原理是使用全局钩子,监控所有进程,对键盘和鼠标消息进行监控。

     linux下openyoudao较好的实现了这个功能,原理是监控剪切板,划词的同时记录剪切板,然后获得鼠标划词结束后的动作,对取得的文本进行处理并显示出来

二、可行性探究

1、模糊查询遇到一个问题就是像各种搜索引擎的模糊查询都是在输入框生成一个下拉列表,用于显示可选的结果,但是在dash里面的话这一点实现实现起来就有困难,因为dash本身没有这个机制,所以模糊查询的结果就不能呈现出来。

2、划词翻译的机制是利用xlib和管道,用xclip命令获得取词后获得的文本内容。用xlib库获取鼠标取词后完成后的瞬间动作,然后通过管道将剪贴板中的内容交给翻译的进程

#!/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()
上面这段代码是一个demo,还有一个困难即通信问题,因为我们要在dash界面中显示,所以这是个问题,下一步就要对这个问题进行研究和解决。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ubuntu dash python scope