【问题标题】:Python Internationalization (gettext)Python 国际化 (gettext)
【发布时间】:2011-10-07 07:36:00
【问题描述】:

我正在尝试使用 Python 进行国际化。我从一个简单的“Hello, World”脚本开始,现在我掌握了使用 gettext 的基础知识。我在文档中读到将字符串连接在一起,如下所示:

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

不推荐,因为它会拆分要翻译的字符串并可能导致错误(这就是我从文档中了解到的)。

我想知道动态生成字符串的最佳做法是什么 - 例如,99 瓶啤酒。众所周知,写 99 瓶啤酒的程序是很可爱的,但是你会嵌套这样的程序,让它可以国际化吗?通过阅读文档,我想出了以下内容。它相当冗长 - 我想知道您是否有任何关于如何改进代码的 cmets(关于国际化,而不是生成歌曲!)

#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.')

【问题讨论】:

    标签: python internationalization


    【解决方案1】:

    我只通过 Django 使用 gettext 函数,所以我不知道您的代码中的所有内容是否都可以 gettext-API-wise,但该方法本身对我来说看起来不错。就个人而言,我经常在非翻译字符串中使用此类占位符,并在从gettext 获取翻译版本后填充它们。

    【讨论】:

      【解决方案2】:

      说实话,我对 Python 知之甚少,我只在 C++ 中使用过 Gettext。

      您似乎正在为外部化字符串使用占位符和字符串格式。这绝对是好的。如果你做对了(似乎在某种程度上,稍后会更多),翻译者将能够带来不止一种复数形式 - 根据数量,瓶子在某些语言中会有不同的翻译(包括波兰语 - 1 butelka , 2 butelki, 5 butelek...)。

      现在,为什么我认为你本可以做得更好。好吧,问题是你正在连接字符串。在这种情况下,它应该无关紧要,但在真正的句子中,即使是很长的文本,最好不要像你那样分割它,并且希望在句子中嵌入新的行标记。这是因为两个原因:

      1. 翻译后的文本通常比原始文本长,因此您需要一种方法来控制文本换行(换行)。
      2. 通常需要在翻译文本时重新排序句子以使其听起来更好听(或者只是因为目标语言的语法与英语完全不同而需要这样做)。

      【讨论】:

      • 你会推荐什么?我应该有一个小占位符并将整个 99 瓶啤酒字符串放在翻译文件中,还是只删除连接?
      • 我不确定我是否理解正确。但是,我的意思是,与其将歌词变量连接起来,不如分配一个长字符串并将其外部化。它在源文件和 PO(T) 文件中肯定不会很好看,但从翻译的角度来看它更容易处理。
      猜你喜欢
      • 1970-01-01
      • 2011-07-12
      • 2010-10-09
      • 1970-01-01
      • 2011-08-04
      • 2013-08-18
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多