覺得google線上翻譯挺好用的,想寫個小工具可以在本地使用,在網上找了兩個都不太好用(用Python實現調用Google翻譯;Google翻譯之Python篇),
現將我自己實現的代碼貼出來,使用了Regex提取翻譯內容:
View Code
1 # -*- coding:utf-8 -*-
2 import urllib, urllib2
3 import re
4 import locale
5
6 def getTranslateHtml(text):
7 values = {'hl':'zh-CN', 'ie':'utf8', 'text':text, 'langpair':"en|zh-CN"}
8 url = 'http://translate.google.cn/translate_t'
9 data = urllib.urlencode(values)
10 req = urllib2.Request(url, data)
11 req.add_header('User-Agent', "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)")
12 reponse = urllib2.urlopen(req)
13 return reponse.read()
14
15 def getTranslateText(html):
16 rettxt = ''
17 m = re.search('<span id=result_box.*?><span .*?>.*?</span></span>', html)
18 if m is not None:
19 rettxt = re.sub('</?span.*?>', '', m.group(0))
20 return rettxt.decode('utf8').encode(locale.getpreferredencoding())
21
22 if __name__ == '__main__':
23
24 while True:
25 text = raw_input('Enter translate text(q exit):')
26 if text == 'q':
27 break
28
29 print getTranslateText(getTranslateHtml(text))
程式運行效果如下: