Azure AI 文本翻译 Python SDK
Azure AI 文本翻译 Python SDK
Azure AI Translator 文本翻译服务的客户端库,支持实时文本翻译、转写和语言操作。
安装
pip install azure-ai-translation-text环境变量
AZURE_TRANSLATOR_KEY=<your-api-key>
AZURE_TRANSLATOR_REGION=<your-region> # 例如 eastus, westus2
或使用自定义终结点
AZURE_TRANSLATOR_ENDPOINT=https://<resource>.cognitiveservices.azure.com身份验证
使用 API 密钥和区域
import os
from azure.ai.translation.text import TextTranslationClient
from azure.core.credentials import AzureKeyCredential
key = os.environ["AZURE_TRANSLATOR_KEY"]
region = os.environ["AZURE_TRANSLATOR_REGION"]
使用区域创建凭据
credential = AzureKeyCredential(key)
client = TextTranslationClient(credential=credential, region=region)使用 API 密钥和自定义终结点
endpoint = os.environ["AZURE_TRANSLATOR_ENDPOINT"]
client = TextTranslationClient(
credential=AzureKeyCredential(key),
endpoint=endpoint
)
Entra ID (推荐)
from azure.ai.translation.text import TextTranslationClient
from azure.identity import DefaultAzureCredential
client = TextTranslationClient(
credential=DefaultAzureCredential(),
endpoint=os.environ["AZURE_TRANSLATOR_ENDPOINT"]
)
基础翻译
# 翻译为单一语言
result = client.translate(
body=["Hello, how are you?", "Welcome to Azure!"],
to=["es"] # 西班牙语
)
for item in result:
for translation in item.translations:
print(f"翻译结果: {translation.text}")
print(f"目标语言: {translation.to}")
翻译为多种语言
result = client.translate(
body=["Hello, world!"],
to=["es", "fr", "de", "ja"] # 西班牙语, 法语, 德语, 日语
)
for item in result:
print(f"源语言: {item.detected_language.language if item.detected_language else 'unknown'}")
for translation in item.translations:
print(f" {translation.to}: {translation.text}")
指定源语言
result = client.translate(
body=["Bonjour le monde"],
from_parameter="fr", # 源语言为法语
to=["en", "es"]
)语言检测
result = client.translate(
body=["Hola, como estas?"],
to=["en"]
)
for item in result:
if item.detected_language:
print(f"检测到语言: {item.detected_language.language}")
print(f"置信度: {item.detected_language.score:.2f}")
转写 (Transliteration)
将文本从一种脚本转换为另一种脚本:
result = client.transliterate(
body=["konnichiwa"],
language="ja",
from_script="Latn", # 从拉丁脚本
to_script="Jpan" # 转换为日语脚本
)
for item in result:
print(f"转写结果: {item.text}")
print(f"脚本: {item.script}")
词典查询
查找备选翻译和定义:
result = client.lookup_dictionary_entries(
body=["fly"],
from_parameter="en",
to="es"
)
for item in result:
print(f"源词: {item.normalized_source} ({item.display_source})")
for transla
tion in item.translations:
print(f" Translation: {translation.normalized_target}")
print(f" Part of speech: {translation.pos_tag}")
print(f" Confidence: {translation.confidence:.2f}")
## 词典示例
获取翻译的使用示例:
from azure.ai.translation.text.models import DictionaryExampleTextItem
result = client.lookup_dictionary_examples(
body=[DictionaryExampleTextItem(text="fly", translation="volar")],
from_parameter="en",
to="es"
)
for item in result:
for example in item.examples:
print(f"Source: {example.source_prefix}{example.source_term}{example.source_suffix}")
print(f"Target: {example.target_prefix}{example.target_term}{example.target_suffix}")
## 获取支持的语言获取所有支持的语言
languages = client.get_supported_languages()
翻译语言
print("Translation languages:") for code, lang in languages.translation.items(): print(f" {code}: {lang.name} ({lang.native_name})")易写/转写语言
print("\nTransliteration languages:") for code, lang in languages.transliteration.items(): print(f" {code}: {lang.name}") for script in lang.scripts: print(f" {script.code} -> {[t.code for t in script.to_scripts]}")词典语言
print("\nDictionary languages:") for code, lang in languages.dictionary.items(): print(f" {code}: {lang.name}")## 分句
识别句子边界:
result = client.find_sentence_boundaries(
body=["Hello! How are you? I hope you are well."],
language="en"
)
for item in result:
print(f"Sentence lengths: {item.sent_len}")
## 翻译选项result = client.translate(
body=["Hello, world!"],
to=["de"],
text_type="html", # "plain" 或 "html"
profanity_action="Marked", # "NoAction", "Deleted", "Marked"
profanity_marker="Asterisk", # "Asterisk", "Tag"
include_alignment=True, # 包含词对齐
include_sentence_length=True # 包含句子边界
)
for item in result:
translation = item.translations[0]
print(f"Translated: {translation.text}")
if translation.alignment:
print(f"Alignment: {translation.alignment.proj}")
if translation.sent_len:
print(f"Sentence lengths: {translation.sent_len.src_sent_len}")
## 异步客户端from azure.ai.translation.text.aio import TextTranslationClient
from azure.core.credentials import AzureKeyCredential
async def translate_text():
async with TextTranslationClient(
credential=AzureKeyCredential(key),
region=region
) as client:
result = await client.translate(
body=["Hello, world!"],
to=["es"]
)
print(result[0].translations[0].text)
``
客户端方法
| 方法 | 描述 |
|--------|-------------|
| translate | 将文本翻译成一种或多种语言 |transliterate
| | 在不同文字/脚本之间转换文本 |detect
| | 检测文本语言 |find_sentence_boundaries
| | 识别句子边界 |lookup_dictionary_entries
| | 词典翻译查询 |lookup_dictionary_examples
| | 获取使用示例 |get_supported_languages` | 列出支持的语言 |
|
最佳实践
1. 批量翻译 — 在一次请求中发送多条文本(最多 100 条)
2. 指定源语言 — 在已知源语言时指定,以提高准确率
3. 使用异步客户端 — 适用于高并发场景
- 高吞吐量场景
4. 缓存语言列表 — 支持的语言不经常变动
5. 根据应用场景妥善处理脏话/敏感词
6. 翻译 HTML 内容时使用 html text_type
7. 对于需要词语映射的应用,请包含对齐信息 (alignment)
使用场景
本技能适用于执行概览中所描述的工作流或操作。局限性
- 仅在任务明确符合上述范围时使用此技能。
- 不要将输出结果视为特定环境验证、测试或专家评审的替代方案。
- 如果缺少必要的输入、权限、安全边界或验收标准,请停止操作并请求澄清。