如何使用DeepL Pro API进行开发 – wiki大全

Ah, it seems I made a mistake and tried to use a tool that isn’t available to me. I apologize for that. I cannot create files directly.

However, I have prepared the detailed guide you requested. I will present it here for you as a response.


如何使用 DeepL Pro API 进行开发:一份详尽指南

DeepL 以其高质量、细致入微的机器翻译效果而闻名。除了提供网页端和桌面应用外,DeepL 还提供了强大的 API,允许开发者将顶级的翻译功能无缝集成到自己的应用程序、网站和服务中。

本指南将详细介绍如何使用 DeepL Pro API(也适用于 Free 免费版)进行开发,重点将使用官方推荐的 Python 库进行演示。

核心概念:Free API vs Pro API

在开始之前,了解两个版本之间的区别很重要:

特性 DeepL API Free (免费版) DeepL API Pro (专业版)
价格 每月免费翻译 500,000 个字符 基于用量的付费订阅
功能 基础翻译功能 所有功能,包括词汇表、文体控制等
数据安全 文本在翻译后立即删除,提供最高级别的数据保护
API 端点 https://api-free.deepl.com https://api.deepl.com

幸运的是,官方库会自动根据你的 API 密钥类型选择正确的端点。


第一步:准备工作

1. 获取认证密钥 (Authentication Key)

无论是使用免费版还是专业版,你都需要一个认证密钥。

  1. 访问 DeepL 官网 并选择一个适合你的 API 计划(推荐从 Free 计划开始体验)。
  2. 注册账户后,在你的账户设置页面找到 “认证密钥 (Authentication Key)”,并复制它。这个密钥是你的身份凭证,请妥善保管。

2. 安装官方 Python 库

DeepL 官方提供了 Python 客户端库,极大地简化了 API 调用。我们强烈建议使用它。

打开你的终端或命令行,然后运行以下命令进行安装:

bash
pip install --upgrade deepl

这个库支持 Python 3.6 及以上版本。

3. 安全建议:存储你的密钥

切勿将你的认证密钥直接硬编码在代码中,尤其是当你的代码需要被提交到版本控制系统(如 Git)时。最佳实践是使用环境变量。

“`bash

在 Linux 或 macOS 中

export DEEPL_AUTH_KEY=”你的密钥”

在 Windows (CMD) 中

set DEEPL_AUTH_KEY=”你的密钥”

在 Windows (PowerShell) 中

$env:DEEPL_AUTH_KEY=”你的密钥”
“`

在 Python 代码中,你可以这样读取它:

python
import os
auth_key = os.getenv("DEEPL_AUTH_KEY")


第二步:核心功能 – 文本翻译

这是 API 最核心的功能。

1. 基础翻译

下面的例子展示了如何将一句英文翻译成德语。

“`python
import os
import deepl

从环境变量中获取认证密钥

auth_key = os.getenv(“DEEPL_AUTH_KEY”)
if not auth_key:
raise Exception(“请设置 DEEPL_AUTH_KEY 环境变量”)

初始化 Translator

translator = deepl.Translator(auth_key)

text_to_translate = “Hello, world! This is a test.”
target_language = “DE” # 目标语言代码,例如 ‘DE’ (德语), ‘FR’ (法语), ‘ZH’ (中文)

try:
# 执行翻译
result = translator.translate_text(text_to_translate, target_lang=target_language)

# 打印结果
print(f"原文: {text_to_translate}")
print(f"译文 ({target_language}): {result.text}")
print(f"检测到的源语言: {result.detected_source_lang}")

except deepl.DeepLException as e:
print(f”翻译时发生错误: {e}”)

“`

translate_text 会自动检测源语言。如果你想明确指定源语言,可以添加 source_lang 参数,例如 source_lang="EN"

2. 批量翻译

为了提高效率,你可以将一个文本列表一次性发送给 API 进行翻译。

“`python
texts = [
“This is the first sentence.”,
“Here is another one.”,
“And a third for good measure.”
]

results = translator.translate_text(texts, target_lang=”FR”)

for i, res in enumerate(results):
print(f”句子 {i+1}: {res.text}”)
“`


第三步:高级功能 (Pro API)

这些功能通常需要 Pro 订阅。

1. 词汇表 (Glossaries)

词汇表功能非常有用,它可以确保特定的品牌名称、术语或专有名词始终被翻译成你想要的形式。

“`python

定义词汇表条目

entries = {“artist”: “Maler”, “painting”: “Gemälde”}
glossary_name = “ArtTerms”

try:
# 创建一个德语词汇表
my_glossary = translator.create_glossary(
glossary_name,
source_lang=”EN”,
target_lang=”DE”,
entries=entries
)
print(f”词汇表 ‘{my_glossary.name}’ 已创建,ID: {my_glossary.glossary_id}”)

# 在翻译时使用词汇表
text = "The artist is creating a new painting."
result_with_glossary = translator.translate_text(
    text,
    target_lang="DE",
    glossary=my_glossary
)

# 译文会是 "Der Maler erschafft ein neues Gemälde." 而不是通常的 "Der Künstler..."
print(f"使用词汇表的翻译: {result_with_glossary.text}")

# 清理(删除词汇表)
translator.delete_glossary(my_glossary)
print("词汇表已删除。")

except deepl.DeepLException as e:
print(f”词汇表操作失败: {e}”)
“`

2. 控制正式/非正式文体 (Formality)

在翻译到某些语言(如德语、法语、西班牙语等)时,你可能需要控制称谓的正式程度。

formality 参数可选值为:
* "default" (默认)
* "more" (更正式)
* "less" (更非正式)

“`python
text = “How are you?”

翻译成更正式的德语

formal_result = translator.translate_text(text, target_lang=”DE”, formality=”more”)
print(f”正式体 (DE): {formal_result.text}”) # 可能输出 “Wie geht es Ihnen?”

翻译成更非正式的德语

informal_result = translator.translate_text(text, target_lang=”DE”, formality=”less”)
print(f”非正式体 (DE): {informal_result.text}”) # 可能输出 “Wie geht es dir?”
“`

3. 处理 XML/HTML 标签

如果你需要翻译包含 HTML 或 XML 标记的文本,并希望保留这些标记,可以使用 tag_handling 参数。

“`python
html_text = “””

An important article

This is the first paragraph.

“””

使用 tag_handling=’xml’ 来处理标签

translated_html = translator.translate_text(
html_text,
target_lang=”ES”, # 西班牙语
tag_handling=”xml”
)

print(translated_html.text)

输出:

Un artículo importante

Este es el primer párrafo.

“`


第四步:文档翻译

DeepL API 还可以翻译整个文档,并保留大部分原始格式。支持的格式包括 .docx, .pptx, .pdf, .html, .txt 等。

“`python
import os
import deepl

This is a conceptual example.

You would need to have the deepl library installed and a valid auth key.

Also, create a dummy file named ‘document.docx’ for this to run.

Mocking translator for demonstration as we don’t have a real key

class MockTranslator:
def translate_document(self, input_path, output_path, target_lang):
print(f”Simulating translation for {input_path} to {output_path} in {target_lang}”)
with open(output_path, “w”) as f:
f.write(“Translated content.”)

translator = deepl.Translator(os.getenv(“DEEPL_AUTH_KEY”))

translator = MockTranslator() # Using the mock for this example

input_path = “document.docx”
output_path = “document_translated.docx”

假设你有一个名为 ‘document.docx’ 的文件

这里我们先创建一个虚拟的

with open(input_path, “w”) as f:
f.write(“This is a test document.”)

try:
# 翻译文档
translator.translate_document(
input_path,
output_path,
target_lang=”FR”
)
print(f”文档已成功翻译并保存到 {output_path}”)

except Exception as e: # Catching a general exception for the mock
print(f”文档翻译失败: {e}”)
finally:
# 清理创建的虚拟文件
if os.path.exists(input_path):
os.remove(input_path)
if os.path.exists(output_path):
os.remove(output_path)
“`


用量与管理

1. 查询账户用量

你可以随时通过 API 检查你的账户配额和使用情况。

“`python

Conceptual example

try:
# In a real scenario:
# translator = deepl.Translator(os.getenv(“DEEPL_AUTH_KEY”))
# usage = translator.get_usage()

# Mocked response for demonstration
class MockUsage:
    def __init__(self):
        self.character = self.MockCharacter()
    class MockCharacter:
        count = 15000
        limit = 500000
    @property
    def any_limit_reached(self):
        return self.character.count >= self.character.limit

usage = MockUsage()

if usage.any_limit_reached:
    print("警告:已达到一个或多个配额限制。")

print(f"已使用字符数: {usage.character.count}")
print(f"字符总配额: {usage.character.limit}")

except Exception as e:
print(f”获取用量失败: {e}”)
“`

2. 获取支持的语言

语言列表可能会更新,你可以动态获取最新的支持语言列表。

“`python

Conceptual example

In a real scenario:

translator = deepl.Translator(os.getenv(“DEEPL_AUTH_KEY”))

source_languages = translator.get_source_languages()

target_languages = translator.get_target_languages()

Mocked response for demonstration

class MockLang:
def init(self, name, code, supports_formality=False):
self.name = name
self.code = code
self.supports_formality = supports_formality

source_languages = [MockLang(“English”, “EN”), MockLang(“German”, “DE”)]
target_languages = [MockLang(“French”, “FR”), MockLang(“Spanish”, “ES”, True)]

print(“— 源语言 —“)
for lang in source_languages:
print(f”{lang.name} ({lang.code})”)

print(“\n— 目标语言 —“)
for lang in target_languages:
formality_info = ‘(支持文体控制)’ if lang.supports_formality else ”
print(f”{lang.name} ({lang.code}) {formality_info}”)
“`


结论

DeepL API 是一个功能强大且易于使用的工具。通过结合官方 Python 库,开发者可以非常便捷地将高质量的翻译功能集成到各种应用场景中。

从简单的文本翻译到复杂的文档处理和词汇表定制,DeepL API 提供了全面的解决方案。为了获得更深入的信息,请务必查阅 DeepL 官方 API 文档。祝你开发顺利!

滚动至顶部