python模塊babel模塊簡單學習筆記

Intro

Babel is an integrated collection of utilities that assist in internationalizing and localizing Python applications, with an emphasis on web-based applications.python

使用babel最主要就是使用其提供的關於語言國際化和本土化實用命令,實現如下功能:web

  • extrace_messages
  • init_catalog
  • compile_catalog
  • update_catalog

四種工做提供參數有:babel

  • -i 輸入文件
  • -o 輸出文件
  • -d 輸出目錄
  • -D domain名稱
  • -l locale名稱

Command Line Usage

extrace

pybabel extract -o project_name/locale/project_name.pot .app

init

pybabel init -i project_name/locale/project_name.pot -D project_name -d project_name/locale --locale zh_CNdom

compile

pybabel compile -D project_name -d project_name/locale/測試

update

pybable update -D project_name -d project_name/locale/翻譯

Use with Distutils/Setuptools

[extract_messages]
keywords = _ gettext ngettext l_ lazy_gettext
mapping_file = babel.cfg
output_file = project_name/locale/project_name.pot

[init_catalog]
domain = project_name
input_file = project_name/locale/project_name.pot
output_dir = project_name/locale
locale = zh_CN

[compile_catalog]
domain = project_name
directory = project_name/locale

[update_catalog]
domain = project_name
output_dir = project_name/locale
input_file = project_name/locale/project_name.pot

要想執行相應操做只須要執行python setup.py [section_name]便可,好比執行python setup.py extract_messages.code

使用

爲了驗證經過compile_catalog生成的.mo文件是否生效可使用ipython測試.ip

import gettext

# install domain(爲了與上面保持一致, domain值爲project_name), 實際爲.mo文件的名字
gettext.install('project_name', './locale')
gettext.translation('project_name', './locale', languages=['zh_CN']).install(True)

# 假設.po文件中有This is a test, 並翻譯爲: 這是一個測試
print _("This is a test")
輸出: 這是一個測試.
相關文章
相關標籤/搜索