Last active
May 8, 2018 08:20
-
-
Save Honghe/13c9b560f1fd52c396d3a6ea58507b59 to your computer and use it in GitHub Desktop.
Use Google web Translate in Python2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#/usr/bin/env python | |
#coding=utf8 | |
import httplib | |
import md5 | |
import urllib | |
import urllib2 | |
import HTMLParser | |
import random | |
import json | |
import re | |
agent = {'User-Agent':'Mozilla/5.0'} | |
def unescape(text): | |
parser = HTMLParser.HTMLParser() | |
return (parser.unescape(text)) | |
def translateByGoogle(text="", fromLang="auto", toLang="zh-CN"): | |
base_link = "https://translate.google.cn/m?hl=%s&sl=%s&q=%s" | |
text = urllib.quote_plus(text.encode('utf-8')) | |
link = base_link % (toLang, fromLang, text) | |
request = urllib2.Request(link, headers=agent) | |
try: | |
raw_data = urllib2.urlopen(request).read() | |
data = raw_data.decode("utf-8") | |
expr = r'class="t0">(.*?)<' | |
re_result = re.findall(expr, data) | |
if (len(re_result) == 0): | |
result = "" | |
else: | |
result = unescape(re_result[0]) | |
return (result) | |
except Exception as e: | |
print e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment