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")
输出: 这是一个测试.
相关文章
相关标签/搜索