目标:读取剪切板内容,翻译并替换原文。(中文翻译为英文,英文以及其他语言翻译成中文)
1、先安装用于发送HTTP请求的Python库requests
,以及pyperclip
1 2
| pip install requests pip install pyperclip
|
2、python代码:(修改其中deepl-api-key)
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
| import requests import pyperclip
def translate_text(text, api_key): url = "https://api-free.deepl.com/v2/translate" params = { 'auth_key': api_key, 'text': text, 'target_lang': 'EN' } response = requests.post(url, data=params) if response.status_code == 200: result = response.json() detected_lang = result['translations'][0]['detected_source_language']
if detected_lang != "ZH": params['target_lang'] = 'ZH' response = requests.post(url, data=params) if response.status_code == 200: result = response.json()
translated_text = result['translations'][0]['text'] return translated_text else: return "Error:", response.status_code, response.text
def main(): API_KEY = 'deepl-api-key' text = pyperclip.paste() translated_text = translate_text(text, API_KEY) print(translated_text) pyperclip.copy(translated_text)
if __name__ == "__main__": main()
|
3、配合quicker,可以快速进行翻译