| 21 | |
| 22 | |
| 23 | {{{ |
| 24 | #!xml |
| 25 | #!/usr/bin/env python |
| 26 | # -*- coding: utf-8 -*- |
| 27 | import pygtk |
| 28 | import gtk |
| 29 | import gtk.glade |
| 30 | import urllib |
| 31 | import urllib2 |
| 32 | import threading |
| 33 | import re |
| 34 | import sys |
| 35 | |
| 36 | #class trans(threading.Thread): |
| 37 | class trans(threading.Thread): |
| 38 | |
| 39 | def __init__(self): |
| 40 | threading.Thread.__init__(self, name='trans') |
| 41 | self.url='http://fanyi.cn.yahoo.com/translate_txt' |
| 42 | self.text=None |
| 43 | self.trans_in='' |
| 44 | self.trans_out='' |
| 45 | self.text_out=None |
| 46 | self.text_in=None |
| 47 | |
| 48 | def getText(self,widget): |
| 49 | buf=widget.get_buffer() |
| 50 | b,e=buf.get_bounds() |
| 51 | return buf.get_text(b,e) |
| 52 | |
| 53 | def setText(self,widget,text=''): |
| 54 | buf=widget.get_buffer() |
| 55 | buf.set_text(text) |
| 56 | widget.set_buffer(buf) |
| 57 | |
| 58 | def run(self): |
| 59 | self.setText(self.text_out,'正在翻译') |
| 60 | |
| 61 | values={'ei':'UTF-8',\ |
| 62 | 'fr':'',\ |
| 63 | 'lp':'%s_%s' %(self.trans_in,self.trans_out),\ |
| 64 | 'trtext':'%s' %(self.getText(self.text_in).replace('\n','\r\n\r'),)} |
| 65 | data=urllib.urlencode(values) |
| 66 | request=urllib2.Request(self.url,data) |
| 67 | conn=urllib2.urlopen(request) |
| 68 | res=conn.read() |
| 69 | res=re.findall('<div id="pd" class="pd"> (.{1,})</div>',res) |
| 70 | res=res[0].replace('<br/>','\n') |
| 71 | res=res.replace('<dnt> </dnt>','\n') |
| 72 | self.setText(self.text_out,res) |
| 73 | |
| 74 | |
| 75 | class yahooTrans(): |
| 76 | |
| 77 | def __init__(self): |
| 78 | self.ui_file=sys.path[0]+'/ui.glade' |
| 79 | self.widgetTree=gtk.glade.XML(self.ui_file,'window1') |
| 80 | dic={"on_exit_clicked":gtk.main_quit,\ |
| 81 | "on_window1_destroy":gtk.main_quit,\ |
| 82 | "on_to_zh_clicked":self.toZh,\ |
| 83 | "on_to_en_clicked":self.toZh} |
| 84 | self.widgetTree.signal_autoconnect(dic) |
| 85 | |
| 86 | def toZh(self,widget): |
| 87 | print widget.get_name() |
| 88 | t=trans() |
| 89 | t.text_in=self.widgetTree.get_widget('text_in') |
| 90 | t.text_out=self.widgetTree.get_widget('text_out') |
| 91 | if widget.get_name()=='to_zh': |
| 92 | t.trans_in='en' |
| 93 | t.trans_out='zh' |
| 94 | else: |
| 95 | t.trans_in='zh' |
| 96 | t.trans_out='en' |
| 97 | t.setDaemon(True) |
| 98 | t.start() |
| 99 | |
| 100 | def main(self): |
| 101 | gtk.main() |
| 102 | |
| 103 | if __name__=='__main__': |
| 104 | gtk.gdk.threads_init() |
| 105 | app=yahooTrans() |
| 106 | app.main() |
| 107 | }}} |