该项目旨在学习babel,可利用babel实现Python项目国际化
准备好一个main.py,是一个猜数字游戏
pip install babel
可见源码,此处不过多赘述,只给出最简实现
print(_("Welcome to the game, Human")) # 新增的翻译内容
print(_( "Hello Human! What is your name?" ))[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,保存提取的可翻译文本。- .: 表示从当前目录开始扫描所有文件。
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的部分代码块做示范,我们在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次!"
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?" )) # 已修改的翻译内容pybabel extract -F babel.cfg -o locales/messages.pot .
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 "你好人类!你叫什么?"
- 可以看到新增的翻译内容对应的
msgstr为空,需要我们填写。 - 已修改的翻译内容带
#, fuzzy标签,带该标签将不会加载为对应的语言翻译内容(即msgstr对应的字符串),而是输出msgid对应的字符串(即Hello Human! What is your name?),因此我们需要更新msgstr后去除#, fuzzy标签
pybabel compile -d locales