-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate.py
35 lines (31 loc) · 1.03 KB
/
translate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import http.client
import json
import ssl
_unverified_context = ssl._create_unverified_context()
def translate(to_translate, to_language="auto", from_language="auto"):
import re
import html
from urllib.parse import quote
agent = {'User-Agent':
"Mozilla/4.0 (\
compatible;\
MSIE 6.0;\
Windows NT 5.1;\
SV1;\
.NET CLR 1.1.4322;\
.NET CLR 2.0.50727;\
.NET CLR 3.0.04506.30\
)"}
base_link = "/m?tl=%s&sl=%s&q=%s"
to_translate = quote(to_translate, safe="")
link = base_link % (to_language, from_language, to_translate)
conn = http.client.HTTPSConnection("translate.google.com",context = _unverified_context)
conn.request("GET", link,headers=agent)
data=conn.getresponse().read().decode("utf-8")
expr = r'(?s)class="(?:t0|result-container)">(.*?)<'
re_result = re.findall(expr, data)
if (len(re_result) == 0):
result = ""
else:
result = html.unescape(re_result[0])
return (result)