Python翻译脚本

看英文PDF的时候,需要一直复制粘贴翻译太烦了,写了个自动检测剪切板并翻译的脚本。

脚本采用了百度的翻译API,免费的额度个人使用足够了,需要注册一下,美中不足的是不能查询音标。

import time
import random
import json
from hashlib import md5
import pyperclip
import requests

def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()

def en2cn(query):
    appid = '你的百度APPID'
    appkey = '你的百度APPKEY'

    # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
    from_lang = 'en'
    to_lang =  'zh'

    endpoint = 'http://api.fanyi.baidu.com'
    path = '/api/trans/vip/translate'
    url = endpoint + path

    salt = random.randint(32768, 65536)
    sign = make_md5(appid + query + str(salt) + appkey)

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

    r = requests.post(url, params=payload, headers=headers)
    result = r.json()

    return result

def main():
    last_string = pyperclip.paste()
    print(20*'=')
    while True:
        time.sleep(0.2)
        string = pyperclip.paste()
        if string != last_string and string != '':
            output_text = string.replace("\r\n", " ")
            output_text = output_text.replace("\n", " ")
            output_text = output_text.replace("\r", " ")
            result = en2cn(output_text)['trans_result'][0]['dst']
            print(result)
            print(20*'=')
            # pyperclip.copy(output_text) # 写入剪切板(能通过API翻译的话,就不需要写入剪切板了)
            last_string = string

if __name__ == '__main__':
    main()