找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 674|回复: 0
打印 上一主题 下一主题

利用谷歌 Translate API制作自己的翻译脚本

[复制链接]

2536

主题

2536

帖子

7532

积分

论坛元老

Rank: 8Rank: 8

积分
7532
跳转到指定楼层
楼主
发表于 2018-2-14 05:58:03 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

            PHP代码:
[U]复制代码[/U] 代码如下:
#!/usr/bin/php -q
text = $text;
}
function translate($from='auto',$to='zh-CN'){
  $this->out = "";
  $gphtml = $this->postPage($this->url, $this->text,$from,$to);
  preg_match_all('/]+>([^/i',$gphtml,$res);
  $this->out = $res[1][0];
  return $this->out;
}
/*
$from  需要翻译的语言
$to    翻译的语言
*/
function postPage($url, $text,$from='auto',$to='zh-CN'){
  $html ='';
  if($url != "" && $text != "") {
   $ch = curl_init($url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   if(!empty($this->ip) && is_string($this->ip)){
    curl_setopt($ch, CURLOPT_INTERFACE,$this->ip);
   }
   curl_setopt($ch, CURLOPT_HEADER, 1);
   curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
   curl_setopt($ch, CURLOPT_TIMEOUT, 15);
   /*
   *hl - 界面语言,此处无用。
   *langpair - src lang to dest lang
   *ie - urlencode的编码方式?
   *text - 要翻译的文本
   */
   $fields = array('hl=zh-CN', 'langpair='.$from.'|'.$to, 'ie=UTF-8','text='.$text);
   $fields = implode('&', $fields);
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
   $html = curl_exec($ch);
   if(curl_errno($ch)) $html = "";
   curl_close ($ch);
  }
  return $html;
}
}
$from = !empty($_REQUEST['fromlan'])?$_REQUEST['fromlan']:'en';
$to = !empty($_REQUEST['tolan'])?$_REQUEST['tolan']:'zh-CN';
$keywords  = "";
for($i=1;$i ip = $_REQUEST['ip'];
}
$article = iconv('GBK','UTF-8',$article);
$article = str_replace('{enter}',"/r/n",$article);
$g->setText($article);
$g->translate($from,$to);
echo "-----------翻译结果--------------/n";
echo iconv('GBK','UTF-8',$g->out);
echo "/n";
?>
2、将以上内容保存名为“gtranslate”的文件中。
3、给gtranslate添加执行权限
    chmod a+x gtranslate
4、创建软连接
    ln -s /yourpath/gtranslate /usr/bin/gtranslate
5、输入测试词汇:
    gtranslate Hello World
    -----------翻译结果--------------
    世界您好
>>>
6、做了个中英文互译的版本。
用 gtranslate China ,英译汉
用 gtranslate -r 中国 ,汉译英
>>>
            
            
您可能感兴趣的文章:
  • JAVA (Jsp)利用Google的Translate开发API的代码
  • PHP Google的translate API代码
  • ASP Google的translate API代码
  • asp.net Google的translate工具翻译 API
  • php调用Google translate_tts api实现代码
            
  • 分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    用户反馈
    客户端