最近写了个小网页,用到了翻译功能。
字幕翻译 - 字幕工具箱
比较了几个翻译API,发现DeepL的翻译质量最好、速度最快。而且,DeepL的翻译API是免费的。所以,今天就来介绍一下如何免费使用DeepL的翻译API。
官方免费API
DeepL翻译API|机器翻译技术
DeepL的API有三个版本:free、pro、企业版。free版本是免费的,但有一些限制。比如,每月最多可以翻译50万字符。个人使用足够了。
注册后,即可获得API Key,用于调用API。
ps: 注册时,需求填写信用卡信息,但不会扣费。这个卡需要是境外的信用卡,国内的银联卡不行。
API调用
调用方法很简单,只需要一个HTTP POST请求。或根据官方文档,使用现成的库。以下为一个Node.js的例子:
Translate text | DeepL API Docs
1
2
3
4
5
6
7
8
9
|
import * as deepl from 'deepl-node';
const authKey = "f63c02c5-f056-..."; // Replace with your key
const translator = new deepl.Translator(authKey);
(async () => {
const result = await translator.translateText('Hello, world!', null, 'fr');
console.log(result.text); // Bonjour, le monde !
})();
|
Deeplx
OwO-Network/DeepLX: DeepL Free API (No TOKEN required)
DeepLX 是一个开源项目,它基于 DeepL 免费服务,将其转换为本地 API,提供给第三次程序使用,如沉浸式翻译、BOb。它不需要 TOKEN,也不需要注册,直接使用。
接口调用
你可以直接调用接口:https://api.deeplx.org/translate。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"text": "Hello, world!",
"source_lang": "auto",
"target_lang": "ZH"
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://api.deeplx.org/translate", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
|
Deeplx NPM
你也可以直接使用打包好的NPM包:deeplx - npm,
都不用写请求代码,直接调用API。
1
2
3
4
|
import { translate } from 'deeplx'
translate('你好', 'NL')
// hello
|
参考资料