-
Notifications
You must be signed in to change notification settings - Fork 1
/
crawl.py
27 lines (20 loc) · 895 Bytes
/
crawl.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
# Obtained from https://www.perfcode.com/p/python-calls-google-translate-api.html with sincere gratitude
import re
import html
from urllib import parse
import requests
GOOGLE_TRANSLATE_URL = 'http://translate.google.com/m?q=%s&tl=%s&sl=%s'
def translate(text, to_language="auto", text_language="auto"):
text = parse.quote(text)
url = GOOGLE_TRANSLATE_URL % (text, to_language, text_language)
response = requests.get(url)
data = response.text
expr = r'(?s)class="(?:t0|result-container)">(.*?)<'
result = re.findall(expr, data)
if len(result) == 0:
return ""
return html.unescape(result[0])
if __name__ == '__main__':
print(translate("你吃饭了么?", "en", "zh-CN")) # 汉语转英语
print(translate("你吃饭了么?", "ja", "zh-CN")) # 汉语转日语
print(translate("about your situation", "zh-CN", "en")) # 英语转汉语