Python国际化(gettext)

0 投票
2 回答
1596 浏览
提问于 2025-04-16 21:43

我正在尝试在Python中进行国际化。最开始我写了一个简单的“你好,世界”脚本,现在我对使用gettext的基本知识有了一定的了解。我在文档中看到,像这样拼接字符串:

msg = _('Start of message')
msg += _(' end of message')

是不推荐的,因为这样会把需要翻译的字符串分开,可能会导致错误(这是我从文档中理解的)。

我在想,对于动态生成的字符串,最佳实践是什么,比如“99瓶啤酒”。大家都知道,写“99瓶啤酒”的程序可以很有趣,但要如何组织这个程序,以便它可以进行国际化呢?通过阅读文档,我想出了以下方法。虽然这个方法比较详细,但我想知道你们有没有什么建议,能让我在国际化方面改进代码(而不是生成这首歌的代码!)

#self._ is gettext.ugettext
#self._s is gettext.ungettext
def bottles(self):
    for bottles in xrange(99, 1, -1):
        lyric =self._s('%(bottles)d bottle of beer on the wall, %(bottles)d bottles of beer.', '%(bottles)d bottles of beer on the wall, %(bottles)d bottles of beer.', bottles)
        lyric += "\n"
        lyric += self._s('Take one down and pass it around, no more bottles of beer on the wall.', 'Take one down and pass it around, %(bottles-1)d bottles of beer on the wall.', bottles - 1)
        lyric += '\n'
        print lyric % {'bottles' : bottles, 'bottles-1' : bottles -1}
    print self._('1 bottle of beer on the wall, 1 bottle of beer.')
    print self._('Take one down and pass it around, no more bottles of beer on the wall.\n')
    print self._('No more bottles of beer on the wall, no more bottles of beer.')
    print self._('Go to the store and buy some more, 99 bottles of beer on the wall.')

2 个回答

0

我只通过Django使用gettext函数,所以不太确定你代码里的所有内容在gettext的使用上是否正确,但就我个人来看,这个方法本身看起来没问题。通常我会在没有翻译的字符串里使用这样的占位符,然后在拿到翻译版本后再填充它们。

1

老实说,我对Python了解不多,只用过C++里的Gettext。

看起来你在使用占位符和字符串格式化来处理外部字符串,这样做是很好的。如果你做得对(看起来在某种程度上是这样,稍后再说),翻译人员就能根据数量提供多种复数形式——比如在某些语言中,“瓶子”的翻译会根据数量不同而不同(比如波兰语:1 butelka, 2 butelki, 5 butelek...)。

现在,我觉得你可以做得更好。问题在于你把字符串拼接在一起。在这种情况下可能没关系,但在真实的句子中,即使是比较长的文本,也最好不要像你那样拆分,最好在句子中嵌入换行符。这有两个原因:

  1. 翻译后的文本通常比原文长,所以你需要控制文本换行的方式(换行符)。
  2. 翻译时常常需要重新排列句子,以便听起来更自然(或者因为目标语言的语法和英语完全不同,这样做是必须的)。

撰写回答