星期二, 9月 15, 2009

Python 練習 - Google translate

因為看了A Bit? No!!!的這篇:写了个小小的翻译工具而做的小小練習。
基本上是作中翻英,但只要稍稍更動 langpair,就可以調整翻譯語言。


#!/usr/bin/env python
# -*= coding: utf-8 -*-
# http://www.oreillynet.com/pub/h/476 Encode Text for URLs
# http://evanjones.ca/python-utf8.html How to Use UTF-8 with Python
# http://abitno.linpie.com/a-small-translate-tool.html 寫了一個小小的翻譯工具
import sys
import os
from urllib import urlencode
import urllib2
import json

def get_json( uri ):
response = urllib2.urlopen( uri )
return response

def translate( text ):
uri="http://www.ajax.googleapis.com/ajax/services/language/translate"
query=urlencode( { 'v': '1.0', 'langpair': 'zh|en', 'q':
text.encode('utf-8') } )
uri = uri+"?"+query
return json.load( get_json( uri ) )

text = unicode( sys.argv[1], "utf-8" )
print unicode( text ) + u" => " + translate( text )['responseData']['translatedText']

沒有留言:

您或許對這些文章有興趣

Related Posts Plugin for WordPress, Blogger...