azure-ai-translation-text-py

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Azure AI Text Translation SDK for Python

适用于Python的Azure AI文本翻译SDK

Client library for Azure AI Translator text translation service for real-time text translation, transliteration, and language operations.
Azure AI Translator文本翻译服务的客户端库,支持实时文本翻译、音译和语言操作。

Installation

安装

bash
pip install azure-ai-translation-text
bash
pip install azure-ai-translation-text

Environment Variables

环境变量

bash
AZURE_TRANSLATOR_KEY=<your-api-key>
AZURE_TRANSLATOR_REGION=<your-region>  # e.g., eastus, westus2
bash
AZURE_TRANSLATOR_KEY=<your-api-key>
AZURE_TRANSLATOR_REGION=<your-region>  # e.g., eastus, westus2

Or use custom endpoint

Or use custom endpoint

AZURE_TRANSLATOR_ENDPOINT=https://<resource>.cognitiveservices.azure.com
undefined
AZURE_TRANSLATOR_ENDPOINT=https://<resource>.cognitiveservices.azure.com
undefined

Authentication

身份验证

API Key with Region

带区域的API密钥

python
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"]
python
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

Create credential with region

credential = AzureKeyCredential(key) client = TextTranslationClient(credential=credential, region=region)
undefined
credential = AzureKeyCredential(key) client = TextTranslationClient(credential=credential, region=region)
undefined

API Key with Custom Endpoint

带自定义端点的API密钥

python
endpoint = os.environ["AZURE_TRANSLATOR_ENDPOINT"]

client = TextTranslationClient(
    credential=AzureKeyCredential(key),
    endpoint=endpoint
)
python
endpoint = os.environ["AZURE_TRANSLATOR_ENDPOINT"]

client = TextTranslationClient(
    credential=AzureKeyCredential(key),
    endpoint=endpoint
)

Entra ID (Recommended)

Entra ID(推荐)

python
from azure.ai.translation.text import TextTranslationClient
from azure.identity import DefaultAzureCredential

client = TextTranslationClient(
    credential=DefaultAzureCredential(),
    endpoint=os.environ["AZURE_TRANSLATOR_ENDPOINT"]
)
python
from azure.ai.translation.text import TextTranslationClient
from azure.identity import DefaultAzureCredential

client = TextTranslationClient(
    credential=DefaultAzureCredential(),
    endpoint=os.environ["AZURE_TRANSLATOR_ENDPOINT"]
)

Basic Translation

基础翻译

python
undefined
python
undefined

Translate to a single language

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}")
undefined
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}")
undefined

Translate to Multiple Languages

翻译为多种语言

python
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}")
python
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}")

Specify Source Language

指定源语言

python
result = client.translate(
    body=["Bonjour le monde"],
    from_parameter="fr",  # Source is French
    to=["en", "es"]
)
python
result = client.translate(
    body=["Bonjour le monde"],
    from_parameter="fr",  # Source is French
    to=["en", "es"]
)

Language Detection

语言检测

python
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}")
python
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}")

Transliteration

音译

Convert text from one script to another:
python
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}")
将文本从一种脚本转换为另一种:
python
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}")

Dictionary Lookup

词典查询

Find alternate translations and definitions:
python
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}")
查找替代翻译和释义:
python
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}")

Dictionary Examples

词典示例

Get usage examples for translations:
python
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}")
获取翻译的使用示例:
python
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 Supported Languages

获取支持的语言

python
undefined
python
undefined

Get all supported languages

Get all supported languages

languages = client.get_supported_languages()
languages = client.get_supported_languages()

Translation languages

Translation languages

print("Translation languages:") for code, lang in languages.translation.items(): print(f" {code}: {lang.name} ({lang.native_name})")
print("Translation languages:") for code, lang in languages.translation.items(): print(f" {code}: {lang.name} ({lang.native_name})")

Transliteration languages

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]}")
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

Dictionary languages

print("\nDictionary languages:") for code, lang in languages.dictionary.items(): print(f" {code}: {lang.name}")
undefined
print("\nDictionary languages:") for code, lang in languages.dictionary.items(): print(f" {code}: {lang.name}")
undefined

Break Sentence

分句

Identify sentence boundaries:
python
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}")
识别句子边界:
python
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}")

Translation Options

翻译选项

python
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}")
python
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}")

Async Client

异步客户端

python
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)
python
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)

Client Methods

客户端方法

MethodDescription
translate
Translate text to one or more languages
transliterate
Convert text between scripts
detect
Detect language of text
find_sentence_boundaries
Identify sentence boundaries
lookup_dictionary_entries
Dictionary lookup for translations
lookup_dictionary_examples
Get usage examples
get_supported_languages
List supported languages
方法描述
translate
将文本翻译为一种或多种语言
transliterate
在不同脚本之间转换文本
detect
检测文本的语言
find_sentence_boundaries
识别句子边界
lookup_dictionary_entries
词典查询翻译结果
lookup_dictionary_examples
获取使用示例
get_supported_languages
列出支持的语言

Best Practices

最佳实践

  1. Batch translations — Send multiple texts in one request (up to 100)
  2. Specify source language when known to improve accuracy
  3. Use async client for high-throughput scenarios
  4. Cache language list — Supported languages don't change frequently
  5. Handle profanity appropriately for your application
  6. Use html text_type when translating HTML content
  7. Include alignment for applications needing word mapping
  1. 批量翻译 — 一次请求发送多个文本(最多100个)
  2. 已知源语言时指定 — 可提高准确性
  3. 使用异步客户端 — 适用于高吞吐量场景
  4. 缓存语言列表 — 支持的语言不会频繁变更
  5. 适当处理亵渎内容 — 根据应用程序需求调整
  6. 翻译HTML内容时使用html文本类型
  7. 需要单词映射时包含对齐信息