下面是详细讲解“python调用有道智云API实现文件批量翻译”的完整攻略。
import requests
import hashlib
import os
url = 'https://openapi.youdao.com/api'
app_key = '你的应用appKey'
app_secret = '你的应用appSecret'
def get_data(q):
# 根据文本内容生成salt和sign
salt = str(os.times()[0])
sign = hashlib.md5((app_key + q + salt + app_secret).encode('utf-8')).hexdigest()
# 构造要发送的数据
data = {
'q': q,
'from': 'auto',
'to': 'auto',
'appKey': app_key,
'salt': salt,
'sign': sign,
}
return data
def translate_files(file_list):
for file in file_list:
translated_file_path = os.path.splitext(file)[0] + '_translated.txt'
with open(file, 'r', encoding='utf-8') as f:
origin_text = f.read()
data = get_data(origin_text)
response = requests.post(url, data=data)
# 解析API返回的JSON数据
result = response.json()
if 'errorCode' not in result:
# 将翻译结果保存到新文件中
with open(translated_file_path, 'w', encoding='utf-8') as f:
f.write(result['translation'][0])
print('文件 %s 翻译完成,结果保存到 %s' % (file, translated_file_path))
else:
print('翻译出错,错误码为:%d' % result['errorCode'])
示例一:批量翻译当前目录下的所有txt文件
file_list = [file for file in os.listdir('.') if os.path.isfile(file) and os.path.splitext(file)[1] == '.txt']
translate_files(file_list)
示例二:批量翻译指定目录下的所有md文件
dir_path = './目标目录'
file_list = [os.path.join(dir_path, file) for file in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, file)) and os.path.splitext(file)[1] == '.md']
translate_files(file_list)