用Google翻译url从python脚本翻译 [英] translate url with google translate from python script

查看:132
本文介绍了用Google翻译url从python脚本翻译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用来自python脚本的Google翻译:

I'm trying to use google translate from a python script:

#!/usr/bin/env python
from urllib2 import urlopen
from urllib import urlencode

base_url = "http://www.google.com/translate?"
params = (('langpair','en|es'), ('u','http://asdf.com'),)
url = base_url+urlencode(params)
print "Encoded URL: %s" % url 
print urlopen(url).read()

使用它时出现错误403.

I'm getting the error 403 when I use it.

# ./1.py 
Encoded URL: http://www.google.com/translate?langpair=en%7Ces&u=http%3A%2F%2Fasdf.com
Traceback (most recent call last):
...
urllib2.HTTPError: HTTP Error 403: Forbidden

但是,从浏览器访问时,相同的URL可以正常工作.有人可以发现错误吗?还是Google不允许这种使用方式?

However the same URL works fine when accessed from browser. Could anyone spot the error? Or is it that google does not allow this type of usage?

预先感谢

推荐答案

如果Google不允许您这样做,则可以通过Google的API以编程方式转换正常网站的来源.

If Google doesn't let you do this, you could programatically translate the normal website's source via the Google's APIs.

我不久前为此编写了一个函数:

I wrote a function for this a little while back:

def translate(text, src = '', to = 'en'):
  parameters = ({'langpair': '{0}|{1}'.format(src, to), 'v': '1.0' })
  translated = ''

  for text in (text[index:index + 4500] for index in range(0, len(text), 4500)):
    parameters['q'] = text
    response = json.loads(urllib.request.urlopen('http://ajax.googleapis.com/ajax/services/language/translate', data = urllib.parse.urlencode(parameters).encode('utf-8')).read().decode('utf-8'))

    try:
      translated += response['responseData']['translatedText']
    except:
      pass

  return translated

这篇关于用Google翻译url从python脚本翻译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆