閱讀610 返回首頁    go 阿裏雲 go 技術社區[雲棲]


利用google在線翻譯製作自己的翻譯程序之ruby版

剛學ruby時寫的工具,我自己一直在用,放在桌麵上,遇到不懂單詞就得問它。發在railscn上,ranchgirl修改的更為ruby way。

 受blogjava上的帖子啟發,實在是個有趣的主意,寫了個ruby版本的,對俺這等英語一般的同學來說,google在線翻譯經常使用呐,原貼之java版
https://www.blogjava.net/ekinglong/archive/2006/11/12/80704.html?Pending=true

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("https://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: https://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("https://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

最後更新:2017-05-17 11:02:16

  上一篇:go  機器學習:如何在安卓上集成TensorFlow
  下一篇:go  李開複@GMIC:AI時代科學家該不該創業 | 全文+PPT