
Python i18n: 현지화 완벽 가이드
JSON 또는 YAML 번역 파일로 python-i18n을 설정하고 플레이스홀더와 복수형을 처리한 뒤 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로 로케일 파일을 번역하세요. IDE에서 AI 어시스턴트에게 원문 파일 번역을 요청하거나 CI/CD 파이프라인에서 i18n Agent CLI를 사용하세요.
# 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 →