zl程序教程

您现在的位置是:首页 >  其他

当前栏目

利用google在线翻译制作自己的翻译程序之ruby版

2023-03-09 22:23:02 时间
刚学ruby时写的工具,我自己一直在用,放在桌面上,遇到不懂单词就得问它。发在railscn上,ranchgirl修改的更为ruby way。

 受blogjava上的帖子启发,实在是个有趣的主意,写了个ruby版本的,对俺这等英语一般的同学来说,google在线翻译经常使用呐,原贴之java版
http://www.blogjava.net/ekinglong/archive/2006/11/12/80704.html?Pending=true#Post

None.gifrequire 'net/http'
None.gifdef translate
None.gif  txt
=STDIN.gets
None.gif  break 
if txt.strip=='e' or txt.strip=='exit'
None.gif  temp
=txt.split(' ')
None.gif  
if temp[1]=='1' or temp.size==1
None.gif    langpair
='en|zh-CN'
None.gif  
else
None.gif    langpair
='zh-CN|en'
None.gif  end
None.gif 
#使用代理  
None.gif
  $proxy_addr = '127.0.0.1'
None.gif  
$proxy_port = 80
None.gif
None.gif  response 
= Net::HTTP.Proxy($proxy_addr, $proxy_port).post_form(URI.parse("http://translate.google.com/translate_t"),{'text'=>temp[0],'langpair'=>langpair})

None.gif  response
.body =~ /<div id=result_box dir=ltr>(.*)<\/div>/
None.gif  result 
= $1 
None.gif  puts '翻译内容:'+temp[0]
None.gif  puts 
'google返回:'+result
None.gif  puts 
'-------------------退出请打e或者exit---------------'
None.gif  translate
None.gifend
None.giftranslate
None.gif


ranchgirl修改的版本,没有使用递归:
None.gifrequire 'net/http'
None.gifdef usage
None.gif  
"usage: word [lang2 [lang1]]\n" +
None.gif  
"Translate word from lang1 (default en, English) to lang2 (default es, Spanish)\n" +
None.gif  
"ISO language code: http://www.unicode.org/unicode/onlinedat/languages.html" 
None.gifend
None.gifdef translate
None.gif  arr 
= ARGV
None.gif  
if !arr[0] then puts usage; return end
None.gif  arr[
1= "es" unless arr[1]
None.gif  arr[
2= "en" unless arr[2
None.gif  langpair 
= "#{arr[2]}|#{arr[1]}"   
None.gif  response 
= Net::HTTP.post_form(URI.parse("http://translate.google.com/translate_t"),
None.gif                                 {
:text => arr[0], :langpair => langpair})
None.gif  response
.body =~ /<div id=result_box dir=ltr>(.*)<\/div>/
None.gif  result 
= $1 
None.gif  result 
= "No #{langpair} translation available for #{arr[0]}" if result.size == 0
None.gif  puts result
None.gifend
None.giftranslate 
文章转自庄周梦蝶  ,原文发布时间5.17