1 import re
2 import urllib.parse, urllib.request
3 import hashlib
4 import urllib
5 import random
6 import json
7 import time
8 from translate import Translator
非python自带的库,如python google translator,需要手动安装,命令pip install module_name。
1. 百度翻译
1 appid = 'your_appid'
2 secretKey = 'your_secretKey'
3 url_baidu = ''
2 reg_text = re.compile(r'(?<=TRANSLATED_TEXT=).*?;')
3 user_agent = r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' \
4 r'Chrome/44.0.2403.157 Safari/537.36'
5
6 def translateGoogle(text, f='ja', t='zh-cn'):
7 values = {'hl': 'zh-cn', 'ie': 'utf-8', 'text': text, 'langpair': '%s|%s' % (f, t)}
8 value = urllib.parse.urlencode(values)
9 req = urllib.request.Request(url_google + '?' + value)
10 req.add_header('User-Agent', user_agent)
11 response = urllib.request.urlopen(req)
12 content = response.read().decode('utf-8')
13 data = reg_text.search(content)
14 result = data.group(0).strip(';').strip('\'')
15 print(result)
和上面两种方法一样,采用的是访问网页的形式来进行翻译。
还有一种是利用python谷歌翻译模块Translator:
1 def translateGoogle2(text):
2 result = translator.translate(text)
3 print(result)
4. 测试代码
测试过程:
翻译5个字串为一个小的单位,输出消耗时间;
循环10次为一个大的单位,输出消耗时间;
对不同的语言字串和循环次数做过多次测试,发现情况基本类似,所以这里选择了10次。
1 text_list = ['こんにちは', 'こんばんは', 'おはようございます', 'お休(やす)みなさい', 'お元気(げんき)ですか']
2
3 time_baidu = 0
4 time_youdao = 0
5 time_google = 0
6 time_google2 = 0
7
8 for i in list(range(1, 11)):
9 time1 = time.time()
10 for text in text_list:
11 translateBaidu(text)
12 time2 = time.time()
13 print('百度翻译第%s次时间:%s' % (i, time2 - time1))
14 time_baidu += (time2 - time1)
15
16 time1 = time.time()
17 for text in text_list:
18 translateYoudao(text)
19 time2 = time.time()
20 print('有道翻译第%s次时间:%s' % (i, time2 - time1))
21 time_youdao += (time2 - time1)
22
23 time1 = time.time()
24 for text in text_list:
25 translateGoogle(text)
26 time2 = time.time()
27 print('谷歌翻译第%s次时间:%s' % (i, time2 - time1))
28 time_google += (time2 - time1)
29
30 time1 = time.time()
31 for text in text_list:
32 translateGoogle2(text)
33 time2 = time.time()
34 print('谷歌2翻译第%s次时间:%s' % (i, time2 - time1))
35 time_google2 += (time2 - time1)
36
37
38 print('百度翻译时间:%s' % (time_baidu / 10))
39 print('有道翻译时间:%s' % (time_youdao / 10))
40 print('谷歌翻译时间:%s' % (time_google / 10))
41 print('谷歌2翻译时间:%s' % (time_google2 / 10))