google-api-translate-java

潘智刚
2023-12-01

google-api-translate-java提供了一个用于调用谷歌翻译,简单的、非官方的java客户端API

项目地址在http://code.google.com/p/google-api-translate-java/

在项目的Quickstart中给出一个Hello World的例子。

 

 

import com.google.api.translate.Language;
import com.google.api.translate.Translate;

public class Main {
  public static void main(String[] args) {
    try {
      String translatedText = Translate.translate("Salut le monde", Language.FRENCH, Language.ENGLISH);
      System.out.println(translatedText);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

 

 

还有一个Python版本的小工具:

 

#!/usr/bin/env python
#coding=utf-8
#!/usr/bin/python
import urllib2
import urllib
import HTMLParser
import sgmllib

class TranstParser(sgmllib.SGMLParser):
    def __init__(self):
        sgmllib.SGMLParser.__init__(self)
        self.results=[]
        self.indata=False

    def start_div(self,attrs):
        divs=[v for k,v in attrs if k=='id']

        if 'result_box' in divs:
            self.indata=True
            

    def handle_data(self,data):
        if self.indata:
            self.results.append(data)
            self.indata=False
lin = 'en'
lout = 'zh_CN'
#lout = 'en'
text = 'Huazhong University of Science & Technology'
req_data={"hl":"zh-cn","ie":"UTF-8",'text':text,"langpair":"%s|%s" % (lin,lout)}
req_url='http://translate.google.cn/translate_t'

data=urllib.urlencode(req_data)
req=urllib2.Request(req_url,data)

req.add_header('User-Agent','Mozilla/4.0')
data=urllib2.urlopen(req).read()
#print data

tp=TranstParser()
tp.feed(data)

for a in tp.results:
    print a

  

 类似资料: