2007-09-04
ruby Tk版本的google翻译机
关键字: google 翻译
过去写的那个调用google翻译的翻译脚本,一直在用。那个版本只能处理单个单词,如果要翻译一行或者一段语句,尽管稍微修改下就可以,但失去了我想要 的便利性。今天看了看TK,顺手写了个GUI版本的,采用一次请求一个线程,倒是便捷不少。在windows上,你需要到这里下载安装ActiveTcl才可以运行。
代码如下:
代码如下:
ruby 代码
- require 'net/http'
- require 'tk'
- require 'logger'
- #设置代理
- $proxy_addr='x.xx.x'
- $proxy_port='80'
- class GoogleTranslate
- def initialize(url)
- @log = Logger.new("translate.log")
- @log.level = Logger::WARN
- @url=url
- ph={'padx'=>50,'pady'=>10}
- root=TkRoot.new{ title 'google 翻译程序'}
- top=TkFrame.new(root) {background "white"}
- #checkbutton,用于选择翻译类别
- checked=TkVariable.new
- TkCheckButton.new(top) do
- text 'cn-en'
- variable checked
- pack({'padx'=>8,'pady'=>10})
- end
- TkLabel.new(top){ text 'Enter text:';pack(ph)}
- @text=TkVariable.new
- @result=TkVariable.new
- TkEntry.new(top,'textvariable'=>@text,'width'=>40).pack(ph)
- pig_b=TkButton.new(top){text '翻译';pack ph}
- #翻译按钮事件
- pig_b.command{ translate(checked.value) }
- TkLabel.new(top){ text 'Translate Result:';pack(ph)}
- TkEntry.new(top,'textvariable'=>@result,'width'=>40).pack(ph)
- pig_a=TkButton.new(top) do
- text 'Exit'
- pack ph
- command {exit}
- end
- top.pack('fill'=>'both','side'=>'top')
- end
- def translate(checked)
- langpair='en|zh-CN'
- langpair='zh-CN|en' if checked=='1'
- #开一个新线程处理
- Thread.new do
- begin
- #使用了代理,如果没有,将Proxy方法去掉 response=Net::HTTP.Proxy($proxy_addr,$proxy_port).post_form(URI.parse(@url),
- {'text'=>@text.value,'langpair'=>langpair})
- response.body =~ /
- @result.value=$1
- rescue Exception=>e
- @log.error(e)
- end
- end
- end
- end
- GoogleTranslate.new("http://translate.google.com/translate_t")
- Tk.mainloop
- 15:54
- 浏览 (838)
- 评论 (0)
- 分类: ruby & rails
- 相关推荐
发表评论
我的留言簿
-
你好,看过你关于自定义classloader的回帖,想问问几个问题:
  ...
-- by llp20_2000
最近加入圈子
最新评论
-
Ruby Tip——读文件
花花公子 写道IO.read("test.log")嗯,这个方法我是知道的,我前 ...
-- by dennis_zane -
Ruby Tip——读文件
IO.read("test.log")
-- by 花花公子 -
一封邮件
咋我没收到呢....
-- by yangzhihuan -
漂亮的代码
说得比较深.看的时候,觉得句句都正中心坎.看完之后,好像没啥收获.还是要自己试过 ...
-- by yangzhihuan -
广州opensource camp小记
貌似你那件open source camp的T-shirt背后很多广告滴说.
-- by yangzhihuan







评论排行榜