Home Backend Development Python Tutorial 使用Python3中的gettext模块翻译Python源码以支持多语言

使用Python3中的gettext模块翻译Python源码以支持多语言

Jun 10, 2016 pm 03:16 PM
gettext python

你写了一个Python 3程序,还想要它适用于其他语言。你能复制全部代码库,然后刻意地检查每个.py文件,替换掉所有找到的文本字符串。但这意味着你有两份你代码的独立副本,每当你要做出个改动或修复个bug,你的工作量会加倍。而且如果你想要程序还适用于其他语言,就更糟了。

幸运的是,Python给了一个解决办法,就是用gettext模块。
一个Hack解法

你应该把你自己的解决办法统一改变。例如,你可以把你程序中的每个字符串替换为一个函数调用(函数名简单些,比如像_()一样),这会返回被翻译为该正确语言的字符串。举个例子,如果你的程序原本是:
 

print('Hello world!')
Copy after login

……你可以将它改为:

print(_('Hello world!'))
Copy after login

……函数_()会返回'Hello world!'的翻译,它基于程序设置有的语言。比如,如果这个语言设置之前被存在一个叫LANGUAGE的全局变量中,函数_()看起来像这样:

def _(s):
  spanishStrings = {'Hello world!': 'Hola Mundo!'}
  frenchStrings = {'Hello world!': 'Bonjour le monde!'}
  germanStrings = {'Hello world!': 'Hallo Welt!'}
 
  if LANGUAGE == 'English':
    return s
  if LANGUAGE == 'Spanish':
    return spanishStrings[s]
  if LANGUAGE == 'French':
    return frenchStrings[s]
  if LANGUAGE == 'German':
    return germanStrings[s]
Copy after login

这可以,但是你这是在重复造轮子。Python的gettext模块可以做更多。gettext是一系列工具,文件格式在20世纪90年代被发明出来,来规范软件国际化(也叫I18N)。gettext是个作为对于所有编程语言的系统化的设计,但是我们会在本篇文章中只专注于Python。
程序例子

设想你有个想要翻译的用Python3写的简单“猜数字”游戏。程序的源代码在这里。有四步来使这个程序国际化:

调整这个.py文件的源代码,这样使字符串输入进一个名为_()的函数。
用和Python一起安装的pygettext.py文本,从源代码创建一个”pot”文件。
用这个免费的跨平台Poedit软件,从pot文件创建.po和.mo文件。
再次调整你的.py文件源代码导入gettext模块的代码,设置语言。

第一步:添加 _() 函数

首先,检查你程序中的所有需要被翻译和用_()的调用来替代的字符串。针对Python使用的gettext系统用_()作为得到翻译了的字符串的通用名,因为它是个短名。

注意:用格式型字符串而不是连接型字符串会是你的程序翻译起来更简单。例如,用连接型字符串你的程序会像这样:

print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
print(_('Good job, ') + myName + _('! You guessed my number in ') + guessesTaken + _(' guesses!'))
Copy after login

This results in three separate strings that need to be translated, as opposed to the single string needed in the string formatting approach:
这会导致三个独立的字符串都需要翻译,然而相反的是在格式型的字符串中,只需翻译一个字符串:

print('Good job, %s! You guessed my number in %s guesses!' % (myName, guessesTaken))
print(_('Good job, %s! You guessed my number in %s guesses!') % (myName, guessesTaken))

当你改完“猜数字”源代码后,它会像这样。你并不能运行它,因为_()函数还没定义。这个变化只是让pygettext.py文本可以找到所有需要翻译的字符串。
第二步:用pygettext.py提取字符串

在你Python安装(Windows上的C:Python34Toolsi18n)中的Tools/i18n就是pygettext.py文本。对于可译字符串普通 gettext unix 命令解析 C/C++ 源码并且 xgettext unix 命令可以解析其他语言,而pygettext.py则知道怎样去解析Python源码。它会找到所有字符串并产生个”pot”文件。

在Windows上我已经运行了这个文本像这样:

C:>py -3.4 C:Python34Toolsi18npygettext.py -d guess guess.py
Copy after login

这创建了一个pot文件,叫guess.pot。这只是个普通纯文本文件,它列出来了全部的在源码中寻找_()的调用的要翻译的字符串。你可以在这儿看guess.pot文件.
第三步:用Poedit翻译字符串

你可以用文本编辑器填写翻译但是免费的Poedit软件会更容易从这儿下载http://poedit.net. 选择 > New from POT/PO file… 然后选择你的guess.po文件。

2015331154815199.jpg (690×720)

Poedit会问你想要翻译成什么语言。我们举例用西班牙语:

2015331154910720.jpg (690×745)

填写翻译吧。(我用 http://translate.google.com,所以对于真的使用西班牙语的人会感觉有点奇怪。)

2015331154956050.jpg (690×581)

现在储存文件在它的gettext形式的文件夹里。保存会创建.po文件(一个人类可读的文本文件不同于原始.pot文件,除了是有西语翻译的)和一个.mo文件(一个gettext会读取的机器可读版本。这些文件会存在一个特定的文件夹内,为的是让gettext能够找到他们。他们看起来像这样(比如西语文件中的”es”和德语文件中”de”):

./guess.py
./guess.pot
./locale/es/LC_MESSAGES/guess.mo
./locale/es/LC_MESSAGES/guess.po
./locale/de/LC_MESSAGES/guess.mo
./locale/de/LC_MESSAGES/guess.po
Copy after login

这些两种性质的语言像西语中的”es”和德语中的 ”de” 被称作ISO 639-1 codes 是语言的标准缩写。你不一定要用他们,但是遵循标准是有道理的。
第四步:给你程序加上gettext代码

现在你有包含翻译的.mo文件,调整你的Python代码去用它。在你的程序中加上下面的:

import gettext
es = gettext.translation('guess', localedir='locale', languages=['es'])
es.install()
Copy after login

第一个 'guess' 是”定义域”,这其实是意味着guess.mo文件名中“猜”的部分。 localedir是你创建的locale文件夹的目录地址。这会是相对或绝对的路径。'es'描述在locale文件夹下面的文件。LC_MESSAGES文件夹是个标准名

install()方法会导致调用_()返回翻译为西语的字符串。如果你想回到原始的英语只需要分配一个lambda函数值给_,这会返回当时输入的字符串:

import gettext
es = gettext.translation('guess', localedir='locale', languages=['es'])
print(_('Hello! What is your name?')) # prints Spanish
 
_ = lambda s: s
Copy after login

你可以检查准备翻译的”Guess the Number”源码。如果你想要运行此程序,下载并解压这个压缩文件和它的locale文件夹和.mo安装文件。
延伸阅读

我怎样都称不上是 I18N or gettext的专家,如果我的教程讲解不够好,请一定要留言。大多数情况下,你的软件运行时不会转换语言,而是会去读LANGUAGE,LC_ALL,LC_MESSAGES,和LANG这些环境变量中的一个来确定计算机的工作地点。我会边学习边更新本教程的。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Debian Apache logs to improve website performance How to use Debian Apache logs to improve website performance Apr 12, 2025 pm 11:36 PM

This article will explain how to improve website performance by analyzing Apache logs under the Debian system. 1. Log Analysis Basics Apache log records the detailed information of all HTTP requests, including IP address, timestamp, request URL, HTTP method and response code. In Debian systems, these logs are usually located in the /var/log/apache2/access.log and /var/log/apache2/error.log directories. Understanding the log structure is the first step in effective analysis. 2. Log analysis tool You can use a variety of tools to analyze Apache logs: Command line tools: grep, awk, sed and other command line tools.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The role of Debian Sniffer in DDoS attack detection The role of Debian Sniffer in DDoS attack detection Apr 12, 2025 pm 10:42 PM

This article discusses the DDoS attack detection method. Although no direct application case of "DebianSniffer" was found, the following methods can be used for DDoS attack detection: Effective DDoS attack detection technology: Detection based on traffic analysis: identifying DDoS attacks by monitoring abnormal patterns of network traffic, such as sudden traffic growth, surge in connections on specific ports, etc. This can be achieved using a variety of tools, including but not limited to professional network monitoring systems and custom scripts. For example, Python scripts combined with pyshark and colorama libraries can monitor network traffic in real time and issue alerts. Detection based on statistical analysis: By analyzing statistical characteristics of network traffic, such as data

How debian readdir integrates with other tools How debian readdir integrates with other tools Apr 13, 2025 am 09:42 AM

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

Nginx SSL Certificate Update Debian Tutorial Nginx SSL Certificate Update Debian Tutorial Apr 13, 2025 am 07:21 AM

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

How to configure HTTPS server in Debian OpenSSL How to configure HTTPS server in Debian OpenSSL Apr 13, 2025 am 11:03 AM

Configuring an HTTPS server on a Debian system involves several steps, including installing the necessary software, generating an SSL certificate, and configuring a web server (such as Apache or Nginx) to use an SSL certificate. Here is a basic guide, assuming you are using an ApacheWeb server. 1. Install the necessary software First, make sure your system is up to date and install Apache and OpenSSL: sudoaptupdatesudoaptupgradesudoaptinsta

See all articles