申请百度翻译Key

申请百度翻译ID和KEY

由于zotero翻译插件的需要,如果使用免费的也很好用,但是翻译的速度和效果不是很好。于是决定今天尝试一下那些需要开通api的服务。由于自己本身就有百度帐号,所以直接使用百度帐号登录 翻译开放平台 , 然后点击 个人开发者→开通通用翻译API → 开发者信息右侧就可以看到申请的ID和Key 了。此处可以参考 百度翻译Key申请教程

设置zotero翻译

打开zotero → 编辑 → 首选项 →翻译 →翻译服务 →百度 →密钥 填入ID#Key → 配置完毕。

设置GoldenDict词典

经过百度得到一个Python脚本,为了方便使用,放在此处。

 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#! /usr/bin/env python3
# vim:fenc=utf-8
#
# Copyright © 2023 feng <feng@archlinux>
#
# Distributed under terms of the MIT license.
import sys
import requests
import random
import json
from hashlib import md5

# 设置应用程序的 appid 和 appkey
appid = 'Your Baidu ID'
appkey = 'Your Baidu Key'

# 源语言和目标语言
from_lang = 'en'
to_lang = 'zh'

# API 相关参数
endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path

# 生成随机数作为 salt
def generate_salt():
    return str(random.randint(32768, 65536))

# 计算签名
def calculate_sign(appid, source, salt, appkey):
    sign_str = appid + source + salt + appkey
    return md5(sign_str.encode('utf-8')).hexdigest()

# 发送翻译请求
def translate_text(source_text):
    salt = generate_salt()
    sign = calculate_sign(appid, source_text, salt, appkey)

    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {
            'appid': appid,
            'q': source_text,
            'from': from_lang,
            'to': to_lang,
            'salt': salt,
            'sign': sign
            }

    response = requests.post(url, params=payload, headers=headers)

    if response.status_code == 200:
        return response.text
    else:
        return None

# 提取翻译结果
def extract_translation(response_text):
    try:
        result = json.loads(response_text)
        translations = result.get('trans_result', [])
        if translations:
            translation0 = translations[0]
            return translation0.get('dst', '')
        else:
            return 'No translation result found.'
    except json.JSONDecodeError:
        return 'Failed to parse JSON response.'

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python3 baidu.py <sentence>")
        sys.exit(1)

    source_text = sys.argv[1]
    response_text = translate_text(source_text)
    translation_text = extract_translation(response_text)
    print(translation_text)

将baidu.py放于GoldenDict的词曲存放目录,然后依次编辑→词曲→程序→添加→类型(纯文本)→名称(baidu) → 命令行

1
python3 /home/feng/.GoldenDict/baidu.py %GDWORD%

→确认→配置完毕。

{% note warning %} 注意:在命令行中,必须使用绝对路径,否则不能正常使用。同时不要忘记给baidu.py赋上执行权限,即执行命令

1
sudo chmod +x /home/feng/.GoldenDict/baidu.py

{% endnote %}