Python 谷歌翻译

#coding=utf-8

import re
import urllib
import urllib2

url_google = 'http://translate.google.cn'
reg_text = re.compile(r'(?<=TRANSLATED_TEXT=).*?;')
user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' \
                 r'Chrome/44.0.2403.157 Safari/537.36'

def translateGoogle(text, f='', t='zh-cn'):
    values = {'hl': 'zh-cn', 'ie': 'utf-8', 'text': text, 'langpair': '%s|%s' % (f, t)}
    value = urllib.urlencode(values)
    req = urllib2.Request(url_google + '?' + value)
    req.add_header('User-Agent', user_agent)
    response = urllib2.urlopen(req)
    content = response.read().decode('utf-8')
    data = reg_text.search(content)
    result = data.group(0).strip(';').strip('\'')
    print result


if __name__ == '__main__':
    text = "What's your name?"
    translateGoogle(text)
    

 

posted @ 2018-08-14 15:09  右介  阅读(226)  评论(0编辑  收藏  举报