自动为pot文件添加注释

时间:2009-04-13 18:27:22

标签: python localization internationalization

我想从我的py文件中提取某些注释来提供翻译上下文,而不是手动编辑.pot文件,基本上我想从这个python文件中找到:

# For Translators: some useful info about the sentence below
_("Some string blah blah")

到这个底池文件:

# For Translators: some useful info about the sentence below
#: something.py:1
msgid "Some string blah blah"
msgstr ""

2 个答案:

答案 0 :(得分:2)

经过多次小便,我发现了最好的方法:

#. Translators:
# Blah blah blah
_("String")

然后用a搜索评论。像这样:

xgettext --language=Python --keyword=_ --add-comments=. --output=test.pot *.py

答案 1 :(得分:1)

我打算建议compiler模块,但忽略了评论:

f.py:

# For Translators: some useful info about the sentence below
_("Some string blah blah")

..和编译器模块:

>>> import compiler
>>> m = compiler.parseFile("f.py")
>>> m
Module(None, Stmt([Discard(CallFunc(Name('_'), [Const('Some string blah blah')], None, None))]))

Python 2.6中的AST模块似乎也是这样做的。

不确定是否可行,但如果你使用三引号字符串......

"""For Translators: some useful info about the sentence below"""
_("Some string blah blah")

..您可以使用编译器模块可靠地解析Python文件:

>>> m = compiler.parseFile("f.py")
>>> m
Module('For Translators: some useful info about the sentence below', Stmt([Discard(CallFunc(Name('_'), [Const('Some string blah blah')], None, None))]))

我尝试编写模式完整脚本来提取文档字符串 - 它不完整,但似乎抓住了大多数文档字符串:http://pastie.org/446156(或github.com/dbr/so_scripts

另一个更简单的选择是使用正则表达式,例如:

f = """# For Translators: some useful info about the sentence below
_("Some string blah blah")
""".split("\n")

import re

for i, line in enumerate(f):
    m = re.findall("\S*# (For Translators: .*)$", line)
    if len(m) > 0 and i != len(f):
        print "Line Number:", i+1
        print "Message:", m
        print "Line:", f[i + 1]

..输出:

Line Number: 1
Message: ['For Translators: some useful info about the sentence below']
Line: _("Some string blah blah")

不确定.pot文件是如何生成的,因此我无法对该部分提供任何帮助..