调用百度翻译api批量翻译文本,python脚本实现

调用百度翻译api批量翻译

要求

  • 申请百度翻译 api_key

实现

import pdb
import openpyxl
import requests
import hashlib
import time


# Baidu translation API endpoint
api_url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
app_id = 'xxx'  # Replace with your actual Baidu App ID
api_key = 'xxx'  # Replace with your actual Baidu API key
salt = '1234xx6'


def md5_encrypt(input_string):
    # 创建MD5对象
    md5_hash = hashlib.md5()
    # 将字符串编码为字节对象并更新MD5对象
    md5_hash.update(input_string.encode('utf-8'))
    # 获取MD5加密后的十六进制结果
    return md5_hash.hexdigest()


def get_sign(text, salt):
    sign = app_id + text + salt + api_key
    return sign

to = 'jp'  # Replace with the language code of the target language
# Function to translate text using Baidu translation API
def translate_text(text):
    params = {
        'q': text,
        'from': 'zh',
        'to': to,
        'appid': app_id,  # Replace with your actual Baidu App ID
        'salt': salt,  # Replace with a random number
        'sign': md5_encrypt(get_sign(text, salt))  # Replace with your actual sign
    }
    response = requests.get(api_url, params=params)
    # pdb.set_trace()
    translation = response.json()['trans_result'][0]['dst']
    return translation

# Load the Excel file
workbook = openpyxl.load_workbook('input.xlsx')  # Replace with your actual file name
sheet = workbook.active

# 自定义修改需要翻译的excel的column
col_index = 2  # Replace with the column index of the Chinese text in the Excel file
# Assume the Chinese text is in column A and the translated text will be placed in column B
for index,row in enumerate(sheet.iter_rows()):  # Skip header row
    # pdb.set_trace()
    # 从第几 row 开始翻译
    if index > 1:
        chinese_text = row[col_index].value
        time.sleep(1)
        translated_text = translate_text(chinese_text)
        print(f"{index}: {chinese_text} -> {translated_text}")
        # pdb.set_trace()
        sheet.cell(row=row[col_index].row, column=col_index+2, value=translated_text)

# Save the modified Excel file
workbook.save(f'translated_excel_{to}.xlsx')  # Replace with your desired file name

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值