Skip to content

Instantly share code, notes, and snippets.

@zqqf16
Last active November 29, 2022 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zqqf16/5610235 to your computer and use it in GitHub Desktop.
Save zqqf16/5610235 to your computer and use it in GitHub Desktop.
A command line translation tool.
#!/usr/bin/env python3
import sys
import uuid
import time
import hashlib
import requests
YOUDAO_URL = 'https://openapi.youdao.com/api'
APP_KEY = '4eb54b2bc1173f2b'
APP_SECRET = '1UIEJZpveZNxQq6larTifVecaWHJr3Fo'
green = '\033[0;32m{}\033[0m: \033[0;34m{}\033[0m'
def encrypt(signStr):
hash_algorithm = hashlib.sha256()
hash_algorithm.update(signStr.encode('utf-8'))
return hash_algorithm.hexdigest()
def truncate(q):
if q is None:
return None
size = len(q)
return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]
def translate(q):
data = {}
data['from'] = 'auto'
data['to'] = 'auto'
data['signType'] = 'v3'
curtime = str(int(time.time()))
data['curtime'] = curtime
salt = str(uuid.uuid1())
signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET
sign = encrypt(signStr)
data['appKey'] = APP_KEY
data['q'] = q
data['salt'] = salt
data['sign'] = sign
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post(YOUDAO_URL, data=data, headers=headers)
contentType = response.headers['Content-Type']
if contentType == "audio/mp3":
millis = int(round(time.time() * 1000))
filePath = "合成的音频存储路径" + str(millis) + ".mp3"
fo = open(filePath, 'wb')
fo.write(response.content)
fo.close()
else:
parse(response.json())
def parse(result):
for tran in result['translation']:
print(green.format('翻译', tran))
try:
print('读音: ' + result['basic']['phonetic'])
except:
pass
try:
for explain in result['basic']['explains']:
print('解释: ' + explain)
except:
pass
try:
for web in result['web']:
value_str = ''
for value in web['value']:
value_str += value + ', '
print('[' + web['key'] + '] ' + value_str)
except:
pass
if __name__ == '__main__':
if len(sys.argv) < 2:
exit()
msg = ' '.join(sys.argv[1:])
translate(msg)
@jianbin91
Copy link

厉害

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment