
Python i18n : คู่มือโลคัลไลเซชันอย่างครบถ้วน
ตั้งค่า python-i18n ด้วยไฟล์แปล JSON หรือ YAML จัดการตัวยึดตำแหน่งและพหูพจน์ แล้วทำให้การแปลเป็นอัตโนมัติด้วย AI
ติดตั้ง python-i18n
python-i18n เป็นไลบรารีรองรับหลายภาษาขนาดเล็กสำหรับ Python รองรับไฟล์แปล JSON และ YAML คีย์ซ้อน การแทรกตัวยึดตำแหน่ง และพหูพจน์ให้ทันที
pip install python-i18n# To use YAML translation files instead of JSON:
pip install python-i18n[YAML]กำหนดค่าคำแปล
ตั้งรูปแบบไฟล์ เพิ่มพาธไฟล์แปล และกำหนดภาษาเริ่มต้นกับภาษาสำรอง นำเข้าการกำหนดค่านี้ที่จุดเริ่มต้นของแอปพลิเคชันก่อนเรียกการแปลใดๆ
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)สร้างไฟล์แปล
สร้างหนึ่งไฟล์ต่อภาษาในรูปแบบ JSON หรือ YAML ใช้คีย์ซ้อนเพื่อจัดระเบียบข้อความตามฟีเจอร์หรือหน้า และให้ภาษาต้นฉบับ ซึ่งมักเป็นภาษาอังกฤษ เป็นแหล่งข้อมูลจริงเพียงแห่งเดียว
// 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"
}
}ใช้คำแปลในโค้ด
เรียก i18n.t() พร้อมพาธคีย์ที่คั่นด้วยจุดเพื่อค้นหาข้อความที่แปลแล้ว คุณแทนที่ภาษาแยกในการเรียกแต่ละครั้งได้โดยไม่เปลี่ยนการตั้งค่าส่วนกลาง
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"ตัวยึดตำแหน่งและพหูพจน์
python-i18n รองรับการแทรกตัวยึดตำแหน่งด้วยไวยากรณ์ %{name} และพหูพจน์พื้นฐานด้วยคีย์ย่อย 'zero', 'one' และ 'many' ส่งอาร์กิวเมนต์คีย์เวิร์ดให้ i18n.t() สำหรับทั้งสองฟีเจอร์
# 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"การสลับภาษาขณะรัน
สลับภาษาปัจจุบันแบบส่วนกลางด้วย i18n.set('locale', code) หรือแทนค่าแยกในการเรียกด้วยอาร์กิวเมนต์คีย์เวิร์ด locale ในเฟรมเวิร์กเว็บ ให้ตรวจภาษาที่ผู้ใช้ต้องการจากคำขอแล้วตั้งภาษาก่อนเรนเดอร์
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")การใช้ภาษาสำรองอัจฉริยะด้วย python-i18n-locale-chain
ตามค่าเริ่มต้น python-i18n รองรับภาษาสำรองเพียงภาษาเดียว เมื่อผู้ใช้ pt-BR ไม่มีคำแปล pt-BR ไลบรารีจะข้ามไปใช้ภาษาอังกฤษและมองข้ามคำแปล pt-PT ที่ใช้ได้ดี python-i18n-locale-chain แก้ปัญหานี้ด้วยลำดับภาษาสำรองที่กำหนดค่าได้ ครอบคลุมรูปแบบภาษา 75 รายการ
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()ทำให้การแปลเป็นอัตโนมัติ
เมื่อตั้งค่า i18n เสร็จแล้ว ให้แปลไฟล์ภาษาด้วย AI โดยบอกผู้ช่วย AI ใน IDE ให้แปลไฟล์ต้นฉบับ หรือใช้ CLI ของ i18n Agent ในไปป์ไลน์ 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,esทำให้คุณภาพการแปลเป็นอัตโนมัติ
ข้อผิดพลาดที่พบบ่อย
คำแปลคืนคีย์ดิบ
ไฟล์ YAML ไม่โหลด
การค้นหาคีย์ซ้อนล้มเหลว
การเปลี่ยนภาษารั่วไหลระหว่างคำขอ
โครงสร้างไฟล์ที่แนะนำ
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
└── ...แปลรายการต่อไปนี้ได้ด้วย :
ลองใช้ i18n Agent ตอนนี้
ลากและวางไฟล์แปลของคุณที่นี่
JSON, YAML, PO, XML, CSV, Markdown, Properties
หรือคลิกเพื่อเลือกไฟล์
ภาษาเป้าหมาย
การใช้ภาษาสำรองด้วย python-i18n-locale-chain
เมื่อไม่มีคีย์คำแปลในภาษาตามภูมิภาคอย่าง es-419 python-i18n จะข้ามไปใช้ภาษาเริ่มต้นทันทีแทนที่จะตรวจภาษาหลัก es ก่อน
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 chainดูคู่มือการใช้ภาษาสำรองของเราสำหรับรายการเฟรมเวิร์กที่รองรับทั้งหมดและลำดับสำเร็จรูป 75 รายการ Learn more →