
Python i18n: Hướng dẫn bản địa hóa đầy đủ
Thiết lập python-i18n với tệp bản dịch JSON hoặc YAML, xử lý phần giữ chỗ và dạng số nhiều rồi tự động dịch bằng AI.
Cài đặt python-i18n
python-i18n là thư viện quốc tế hóa gọn nhẹ dành cho Python. Thư viện hỗ trợ sẵn tệp bản dịch JSON và YAML, khóa lồng nhau, nội suy phần giữ chỗ và dạng số nhiều.
pip install python-i18n# To use YAML translation files instead of JSON:
pip install python-i18n[YAML]Cấu hình bản dịch
Đặt định dạng tệp, thêm đường dẫn tệp bản dịch và cấu hình ngôn ngữ mặc định cùng ngôn ngữ dự phòng. Nhập cấu hình này tại điểm vào của ứng dụng trước mọi lệnh gọi dịch.
import i18n
# Set the file format (json or yaml)
i18n.set("file_format", "json")
# Add the directory containing your translation files
i18n.load_path.append("translations/")
# Set the default locale
i18n.set("locale", "en")
# Set the fallback locale (used when a key is missing)
i18n.set("fallback", "en")
# Enable/disable error on missing translations
i18n.set("error_on_missing_translation", False)Tạo tệp bản dịch
Tạo một tệp cho mỗi ngôn ngữ ở định dạng JSON hoặc YAML. Dùng khóa lồng nhau để sắp xếp chuỗi theo tính năng hoặc trang. Giữ ngôn ngữ nguồn (thường là tiếng Anh) làm nguồn tham chiếu duy nhất.
// translations/en.json
{
"greeting": "Hello!",
"welcome": "Welcome to our application",
"nav": {
"home": "Home",
"about": "About",
"settings": "Settings"
},
"cart": {
"item_count": "%{count} item(s) in your cart"
}
}
// translations/de.json
{
"greeting": "Hallo!",
"welcome": "Willkommen in unserer Anwendung",
"nav": {
"home": "Startseite",
"about": "Über uns",
"settings": "Einstellungen"
},
"cart": {
"item_count": "%{count} Artikel in Ihrem Warenkorb"
}
}Dùng bản dịch trong mã của bạn
Gọi i18n.t() bằng đường dẫn khóa phân tách bởi dấu chấm để tra cứu chuỗi đã dịch. Bạn có thể ghi đè ngôn ngữ cho từng lệnh gọi mà không thay đổi cài đặt chung.
import i18n
# Simple translation
print(i18n.t("greeting")) # "Hello!"
print(i18n.t("nav.home")) # "Home"
print(i18n.t("nav.about")) # "About"
# Translation with a specific locale
print(i18n.t("greeting", locale="de")) # "Hallo!"
print(i18n.t("nav.home", locale="ja")) # "ホーム"
# Missing key returns a placeholder
print(i18n.t("missing.key")) # "Missing.Key"Phần giữ chỗ và dạng số nhiều
python-i18n hỗ trợ nội suy phần giữ chỗ bằng cú pháp %{name} và dạng số nhiều cơ bản bằng các khóa con 'zero', 'one' và 'many'. Truyền đối số từ khóa vào i18n.t() cho cả hai tính năng.
# translations/en.json
# {
# "welcome_user": "Welcome, %{name}!",
# "order_status": "Order #%{order_id}: %{status}",
# "file_size": "File size: %{size} %{unit}"
# }
import i18n
# Single placeholder
print(i18n.t("welcome_user", name="Alice"))
# "Welcome, Alice!"
# Multiple placeholders
print(i18n.t("order_status", order_id=12345, status="shipped"))
# "Order #12345: shipped"
# Reusable with different values
print(i18n.t("file_size", size=2.5, unit="MB"))
# "File size: 2.5 MB"
print(i18n.t("file_size", size=800, unit="KB"))
# "File size: 800 KB"# translations/en.json
# {
# "inbox": {
# "zero": "No messages",
# "one": "1 message",
# "many": "%{count} messages"
# }
# }
import i18n
print(i18n.t("inbox", count=0)) # "No messages"
print(i18n.t("inbox", count=1)) # "1 message"
print(i18n.t("inbox", count=42)) # "42 messages"Chuyển đổi ngôn ngữ khi chạy
Chuyển ngôn ngữ đang dùng trên toàn cục bằng i18n.set('locale', code) hoặc ghi đè cho từng lệnh gọi bằng đối số từ khóa locale. Trong framework web, hãy phát hiện ngôn ngữ ưu tiên của người dùng từ yêu cầu và đặt ngôn ngữ trước khi kết xuất.
import i18n
# Set locale globally
i18n.set("locale", "de")
print(i18n.t("greeting")) # "Hallo!"
# Switch to Japanese
i18n.set("locale", "ja")
print(i18n.t("greeting")) # "こんにちは!"
# Override per-call without changing global locale
i18n.set("locale", "en")
print(i18n.t("greeting")) # "Hello!"
print(i18n.t("greeting", locale="de")) # "Hallo!"from flask import Flask, request, g
import i18n
app = Flask(__name__)
i18n.set("file_format", "json")
i18n.load_path.append("translations/")
SUPPORTED_LOCALES = ["en", "de", "ja", "es", "fr"]
@app.before_request
def set_locale():
# Check URL parameter, cookie, then Accept-Language header
locale = request.args.get("lang")
if not locale:
locale = request.cookies.get("locale")
if not locale:
locale = request.accept_languages.best_match(SUPPORTED_LOCALES)
g.locale = locale or "en"
i18n.set("locale", g.locale)
@app.route("/")
def index():
return i18n.t("welcome")Dự phòng ngôn ngữ thông minh với python-i18n-locale-chain
Theo mặc định, python-i18n chỉ hỗ trợ một ngôn ngữ dự phòng. Khi người dùng pt-BR không có bản dịch pt-BR, thư viện chuyển thẳng sang tiếng Anh dự phòng và bỏ qua bản dịch pt-PT hoàn toàn phù hợp. python-i18n-locale-chain khắc phục vấn đề này bằng chuỗi dự phòng có thể cấu hình, bao phủ 75 biến thể ngôn ngữ.
pip install python-i18n-locale-chainfrom locale_chain import configure
import i18n
i18n.set("file_format", "json")
i18n.load_path.append("translations/")
# Activate smart fallback chains (75 built-in chains)
configure()
# Now pt-BR falls back to pt-PT -> pt -> en (instead of just en)
result = i18n.t("greeting", locale="pt-BR")
# es-MX falls back to es-419 -> es -> en
result = i18n.t("greeting", locale="es-MX")
# zh-Hant-HK falls back to zh-Hant-TW -> zh-Hant -> en
result = i18n.t("greeting", locale="zh-Hant-HK")from locale_chain import configure, reset
# Override specific chains
configure(overrides={
"pt-BR": ["pt"], # Skip pt-PT, go straight to pt
"ja-JP": ["ja"], # Add a new chain
})
# Full custom map (no defaults)
configure(
fallbacks={"pt-BR": ["pt-PT"]},
merge_defaults=False
)
# Use German as final fallback instead of English
configure(default_locale="de")
# Restore original i18n.t() behaviour
reset()Tự động hóa bản dịch
Sau khi hoàn tất thiết lập i18n, hãy dùng AI để dịch các tệp ngôn ngữ. Trong IDE, yêu cầu trợ lý AI dịch tệp nguồn hoặc dùng i18n Agent CLI trong quy trình CI/CD.
# In your IDE, ask your AI assistant:
> Translate translations/en.json to German, Japanese, and Spanish
translations/de.json created (1.2s)
translations/ja.json created (1.5s)
translations/es.json created (1.1s)
# Or use the CLI in CI/CD:
npx i18n-agent translate translations/en.json --lang de,ja,esTự động đảm bảo chất lượng bản dịch
Lỗi thường gặp
Bản dịch trả về khóa thô
Không tải được tệp YAML
Không tra cứu được khóa lồng nhau
Thay đổi ngôn ngữ bị rò rỉ giữa các yêu cầu
Cấu trúc tệp đề xuất
my-python-app/
├── translations/
│ ├── en.json # Source language (JSON)
│ ├── de.json # German
│ ├── ja.json # Japanese
│ ├── es.json # Spanish
│ └── pt-BR.json # Brazilian Portuguese
├── app.py # Application entry point
├── i18n_config.py # i18n setup and configuration
├── requirements.txt # pip dependencies
└── pyproject.toml # Project metadata
# Or with YAML files:
my-python-app/
├── translations/
│ ├── en.yml
│ ├── de.yml
│ └── ja.yml
├── app.py
└── ...Dùng thử i18n Agent ngay
Thả tệp bản dịch của bạn vào đây
JSON, YAML, PO, XML, CSV, Markdown, Properties
hoặc nhấp để duyệt
Ngôn ngữ đích
Dự phòng ngôn ngữ với python-i18n-locale-chain
Khi thiếu khóa bản dịch trong ngôn ngữ vùng miền như es-419, python-i18n chuyển thẳng sang ngôn ngữ mặc định thay vì kiểm tra ngôn ngữ cha es trước.
pip install python-i18n-locale-chainfrom i18n_locale_chain import configure_chain
configure_chain('{')
'es': ['en', 'ru'],
'pt-BR': ['pt', 'en'],
'zh-Hant-HK': ['zh-Hant', 'zh', 'en'],
'}')
# Usage: t('greeting', locale='es') — falls back through chainXem Hướng dẫn dự phòng ngôn ngữ để biết danh sách đầy đủ các framework được hỗ trợ và 75 chuỗi tích hợp sẵn. Learn more →