Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 

Repository files navigation

test_babel

该项目旨在学习babel,可利用babel实现Python项目国际化

流程

准备一个程序

准备好一个main.py,是一个猜数字游戏

安装babel

pip install babel

标记可翻译的文本

可见源码,此处不过多赘述,只给出最简实现

print(_("Welcome to the game, Human"))  # 新增的翻译内容
print(_( "Hello Human! What is your name?" ))

创建babel.cfg配置文件

[python: src/**.py]  
encoding = utf-8

提取翻译内容

执行下述命令前应先确保locales文件夹已存在

pybabel extract -F babel.cfg -o locales/messages.pot .
  • pybabel: Flask-Babel 的命令行工具,用于国际化处理。
  • extract: 提取可翻译的字符串。
  • -F babel.cfg: 指定配置文件 babel.cfg,定义了哪些文件需要扫描和提取翻译。
  • -o locales/messages.pot: 指定输出文件 locales/messages.pot,保存提取的可翻译文本。
  • .: 表示从当前目录开始扫描所有文件。

初始化翻译文件,生成po文件

pybabel init -i locales/messages.pot -d locales -l zh_CN
  • -i msg.pot: 使用之前提取的 .pot 文件(messages.pot)作为输入。
  • -d locales: 指定存放翻译文件的目录(locales)。
  • -l zh_CN: 指定目标语言为简体中文 (zh_CN)。

编辑po文件

此处只给出项目中.po的部分代码块做示范,我们在msgstr填入翻译内容

#: src/main.py:30
msgid "Your guess is too high."
msgstr "猜大了"

#: src/main.py:37
#, python-format
msgid "Good job, %s! You guessed my number in %s guesses!"
msgstr "%s,你猜对了,你猜了%s次!"

编译po文件,生成mo文件

pybabel compile -d locales

编译后的 .mo 文件会生成在 locales/zh_CN/LC_MESSAGES/ 目录下,供程序使用。

如何加载对应语言?

本项目中,在main.py调整下述代码块的languages即可

lang = gettext.translation('messages', localedir='locales', languages=['zh_CN'], fallback=True)

翻译内容更新后的处理方法

假设有新增和修改文本,如下

print(_("Welcome to the game, Human"))  # 新增的翻译内容
print(_( "Hello Human! What is your name?" ))   # 已修改的翻译内容

更新.pot文件

pybabel extract -F babel.cfg -o locales/messages.pot .

合并更新到 .po 文件

pybabel update -i locales/messages.pot -d locales

执行该命令后.po文件会出现以下代码块:

#: src/main.py:12
msgid "Welcome to the game, Human"
msgstr 

#: src/main.py:13
#, fuzzy
msgid "Hello Human! What is your name?"
msgstr "你好人类!你叫什么?"
  1. 可以看到新增的翻译内容对应的msgstr为空,需要我们填写。
  2. 已修改的翻译内容带#, fuzzy标签,带该标签将不会加载为对应的语言翻译内容(即msgstr对应的字符串),而是输出msgid对应的字符串(即Hello Human! What is your name?),因此我们需要更新msgstr后去除#, fuzzy标签

重新编译.mo文件

pybabel compile -d locales

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages