我如何使用 json google translate api? [英] how do I use the json google translate api?

查看:85
本文介绍了我如何使用 json google translate api?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有 utf-8 文本的 python 谷歌翻译.我如何调用json api?他们有一个文档可以将它嵌入到 html 中,但我在任何地方都找不到合适的 API 或 wsdl.

I am trying to use google translate from python with utf-8 text. How do I call the json api? They have a document for embedding it in html but I can't find a proper API or wsdl anywhere.

谢谢拉斐尔

推荐答案

这是最终对我有用的代码.使用没有ajax api的网站可以让你的ip被禁止,所以这个更好.

Here is the code that finally works for me. Using the website without the ajax api can get your ip banned, so this is better.

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

# The google translate API can be found here:
# http://code.google.com/apis/ajaxlanguage/documentation/#Examples
def translate(text = 'hola querida'):
    tl="es"
    sl="en"
    langpair='%s|%s'%(tl,sl)



    base_url='http://ajax.googleapis.com/ajax/services/language/translate?'
    data = urllib.urlencode({'v':1.0,'ie': 'UTF8', 'q': text.encode('utf-8'),
                             'langpair':langpair})


    url = base_url+data

    search_results = urllib.urlopen(url)

    json = simplejson.loads(search_results.read())


    result = json['responseData']['translatedText']
    return result

这篇关于我如何使用 json google translate api?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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