Python国际化(gettext)
我正在用Python进行国际化实验。我从一个简单的“Hello,World”脚本开始,现在掌握了使用gettext的基本知识。我在文档中读到,将字符串连接在一起是这样的:Python国际化(gettext),python,internationalization,Python,Internationalization,我正在用Python进行国际化实验。我从一个简单的“Hello,World”脚本开始,现在掌握了使用gettext的基本知识。我在文档中读到,将字符串连接在一起是这样的: msg = _('Start of message') msg += _(' end of message') 不建议使用,因为它会分割要翻译的字符串,并可能导致错误(这是我从文档中理解的) 我想知道动态生成字符串的最佳实践是什么——例如,99瓶啤酒。大家都知道,编写99瓶啤酒的程序非常可爱,但你是否会构建这样一个程序,使其
msg = _('Start of message')
msg += _(' end of message')
不建议使用,因为它会分割要翻译的字符串,并可能导致错误(这是我从文档中理解的)
我想知道动态生成字符串的最佳实践是什么——例如,99瓶啤酒。大家都知道,编写99瓶啤酒的程序非常可爱,但你是否会构建这样一个程序,使其国际化?通过阅读这些文件,我得出以下结论。这相当冗长-我想知道您是否对如何改进代码有任何意见(关于国际化,而不是生成歌曲!)
我只通过Django使用
gettext
函数,所以我不知道代码中的所有内容在gettext API方面是否都正常,但方法本身在我看来是正常的。我个人经常在非翻译字符串中使用这样的占位符,在获得代码“> GETTEX/<代码> > < < /P> > P>之后,将它们填满。老实说,我对Python了解很少,我只使用Gettext和C++。
似乎您正在为外部化字符串使用占位符和字符串格式。这绝对是好的。如果你做得正确(在某种程度上,后面会有更多介绍),翻译人员将能够带来不止一种复数形式——根据数量,瓶子在某些语言中会有不同的翻译(包括波兰语-1布特尔卡语,2布特尔基语,5布特莱克语…)
现在,为什么我认为你可以做得更好。好吧,问题是您正在连接字符串。在这种情况下,这不重要,但在真实的句子中,即使是很长的文本,也最好不要像您那样拆分它,并且希望在句子中嵌入新的行号。这是因为两个原因:
你推荐什么?我应该有一个小的占位符,把整个99瓶啤酒串都放在翻译文件中,还是仅仅删除连接?我不确定我是否理解正确。然而,我的意思是,与其将歌词变量连接起来,不如指定一个长字符串并将其外部化。它在源文件和PO(t)文件中看起来都不是很好,但是从翻译的角度来看,它更容易处理。
#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.')