免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 50282 | 回复: 0
打印 上一主题 下一主题

命令行调用google翻译的ruby脚本 [复制链接]

论坛徽章:
1
2015亚冠之阿尔萨德
日期:2015-07-03 11:07:01
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-03 11:07 |只看该作者 |倒序浏览
  1. require 'uri'
  2. require 'open-uri'
  3. require 'iconv'

  4. CN_re = /(?:\xe4[\xb8-\xbf][\x80-\xbf]|[\xe5-\xe8][\x80-\xbf][\x80-\xbf]|\xe9[\x80-\xbd][\x80-\xbf]|\xe9\xbe[\x80-\xa5])+/n unless defined? CN_re

  5. class String
  6.   def en2zh
  7.     return self if self.force_encoding("ASCII-8BIT") =~ CN_re #有中文
  8.     flg = 'auto%7czh-CN'
  9.     g_tr(self,flg)
  10.   end
  11.   def zh2en
  12.     return self if self.force_encoding("ASCII-8BIT") !~ CN_re #无中文
  13.     flg = 'zh-CN%7cen'
  14.     g_tr(self,flg)
  15.   end
  16.   if RUBY_VERSION < '1.9'
  17.     def force_encoding(s)
  18.       self
  19.     end
  20.   end
  21.   def utf8_to_gb
  22.     Iconv.conv("GB18030//IGNORE","UTF-8//IGNORE",self).to_s
  23.   end
  24.   alias togb utf8_to_gb
  25. end

  26. #google 全文翻译,参数可以是中文,也可以是英文.
  27. def g_tr(word,flg)
  28.   word = URI.escape(word)
  29.   url = "http://translate.google.com/translate_a/t?client=firefox-a&text=#{word}&langpair=#{flg}&ie=UTF-8&oe=UTF-8"
  30.   uri = URI.parse(url)
  31.   uri.open(
  32.    'Accept'=>'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */*',
  33.    'Accept'=>'text/html',
  34.    'Referer'=> URI.escape(url)
  35.    ){ |f|
  36.       return f.read.match(/"trans":"(.*?)","/)[1]
  37.   }
  38. end

  39. #使用方法:
  40. puts 'show me the money'.en2zh
  41. #puts 'show me the money'.en2zh.togb #windows 平台乱码转换
  42. puts '可以整句翻译。'.zh2en

  43. # wget -qO- http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$1&langpair=$2|${3:-en}" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1\n/';
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP