命令行调用google翻译的ruby脚本
发布时间:2020-12-17 04:11:45 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 require 'uri'require 'open-uri'require 'iconv'CN_re = /(?:xe4[xb8-xbf][x80-xbf]|[xe5-xe8][x80-xbf][x80-xbf]|xe9[x80-xbd][x80-
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 require 'uri' require 'open-uri' require 'iconv' CN_re = /(?:xe4[xb8-xbf][x80-xbf]|[xe5-xe8][x80-xbf][x80-xbf]|xe9[x80-xbd][x80-xbf]|xe9xbe[x80-xa5])+/n unless defined? CN_re class String def en2zh return self if self.force_encoding("ASCII-8BIT") =~ CN_re #有中文 flg = 'auto%7czh-CN' g_tr(self,flg) end def zh2en return self if self.force_encoding("ASCII-8BIT") !~ CN_re #无中文 flg = 'zh-CN%7cen' g_tr(self,flg) end if RUBY_VERSION < '1.9' def force_encoding(s) self end end def utf8_to_gb Iconv.conv("GB18030//IGNORE","UTF-8//IGNORE",self).to_s end alias togb utf8_to_gb end #google 全文翻译,参数可以是中文,也可以是英文. def g_tr(word,flg) word = URI.escape(word) url = "http://translate.google.com/translate_a/t?client=firefox-a&text=#{word}&langpair=#{flg}&ie=UTF-8&oe=UTF-8" uri = URI.parse(url) uri.open( 'Accept'=>'image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,application/x-shockwave-flash,*/*','Accept'=>'text/html','Referer'=> URI.escape(url) ){ |f| return f.read.match(/"trans":"(.*?)","/)[1] } end #使用方法: puts 'show me the money'.en2zh #puts 'show me the money'.en2zh.togb #windows 平台乱码转换 puts '可以整句翻译。'.zh2en # wget -qO- http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$1&langpair=$2|${3:-en}" | sed 's/.*"translatedText":"([^"]*)".*}/1n/'; 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |