关于 azure-ai-translation-text-py
面向需要文本翻译及语言处理的应用,提供 Azure AI Translator 的 Python 客户端库。还支持转写、词典查询和句子边界识别。
主要功能
- 01将文本翻译为一种或多种语言
- 02检测源语言
- 03在文字系统间转写
- 04查询词条和用法示例
- 05识别句子边界
- 06列出支持的语言
适用场景
- 01为多语言应用翻译文本
- 02转换不同书写系统间的文本
- 03查询词典释义和用法示例
- 04将文本切分为句子
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill azure-ai-translation-text-py安装后在 Claude Code 中输入/azure-ai-translation-text-py确认已加载。
详细介绍
Azure AI Text Translation SDK for Python
用于 Azure AI Translator 文本翻译服务的客户端库,支持实时文本翻译、转写和语言操作。
安装
pip install azure-ai-translation-text
环境变量
AZURE_TRANSLATOR_KEY=<your-api-key>
AZURE_TRANSLATOR_REGION=<your-region> # e.g., eastus, westus2
# Or use custom endpoint
AZURE_TRANSLATOR_ENDPOINT=https://<resource>.cognitiveservices.azure.com
身份验证
使用区域的 API Key
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"]
# Create credential with region
credential = AzureKeyCredential(key)
client = TextTranslationClient(credential=credential, region=region)
使用自定义终结点的 API Key
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"]
)
基本翻译
# Translate to a single language
result = client.translate(
body=["Hello, how are you?", "Welcome to Azure!"],
to=["es"] # Spanish
)
for item in result:
for translation in item.translations:
print(f"Translated: {translation.text}")
print(f"Target language: {translation.to}")
翻译成多种语言
result = client.translate(
body=["Hello, world!"],
to=["es", "fr", "de", "ja"] # Spanish, French, German, Japanese
)
for item in result:
print(f"Source: {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", # Source is French
to=["en", "es"]
)
语言检测
result = client.translate(
body=["Hola, como estas?"],
to=["en"]
)
for item in result:
if item.detected_language:
print(f"Detected language: {item.detected_language.language}")
print(f"Confidence: {item.detected_language.score:.2f}")
转写
将文本从一种文字转换为另一种文字:
result = client.transliterate(
body=["konnichiwa"],
language="ja",
from_script="Latn", # From Latin script
to_script="Jpan" # To Japanese script
)
for item in result:
print(f"Transliterated: {item.text}")
print(f"Script: {item.script}")
词典查询
查找其他译法和释义:
result = client.lookup_dictionary_entries(
body=["fly"],
from_parameter="en",
to="es"
)
for item in result:
print(f"Source: {item.normalized_source} ({item.display_source})")
for translation 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}")
获取支持的语言
# Get all supported languages
languages = client.get_supported_languages()
# Translation languages
print("Translation languages:")
for code, lang in languages.translation.items():
print(f" {code}: {lang.name} ({lang.native_name})")
# Transliteration languages
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]}")
# Dictionary languages
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" or "html"
profanity_action="Marked", # "NoAction", "Deleted", "Marked"
profanity_marker="Asterisk", # "Asterisk", "Tag"
include_alignment=True, # Include word alignment
include_sentence_length=True # Include sentence boundaries
)
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 | 列出支持的语言 |
最佳实践
- 批量翻译 — 在一次请求中发送多段文本(最多 100 段)
- 已知源语言时,请指定源语言以提高准确性
- 高吞吐量场景下,请使用异步客户端
- 缓存语言列表 — 支持的语言不会频繁变化
- 根据应用需求妥善处理粗俗内容
- 翻译 HTML 内容时,请使用
htmltext_type - 对于需要词语映射的应用,请包含对齐信息
适用场景
当任务与上述概述中所述的工作流或操作明确匹配时,可使用此技能。
限制
- 仅当任务明确符合上述范围时,才使用此技能。
- 不要将输出视为环境特定验证、测试或专家审查的替代品。
- 如果缺少必要的输入、权限、安全边界或成功标准,请暂停并请求澄清。
使用这些代码片段之前,请根据固定的 SDK 和资源 API 版本,验证签名以及批次和字符数限制。翻译文本会将其发送到已配置的云服务;请授权敏感内容传输,并对日志进行脱敏。请处理单项错误、有限重试和配额限制;创建客户端并不代表翻译已成功。
评论
支持 Markdown