发生这种情况的原因是因为xgettext
实际上并未执行您的Python文件,而是以纯文本的形式读取,并尝试识别必须翻译的字符串。在添加_(varaible)
而不是_("literal string that xgettext understands")
时,它不会将其识别为应该翻译的文本。
为了达到这个目的,我能想到的最直接的方法是生成一个虚拟文件,您将输入xgettext
,它将包含所有实际值。现在考虑您的csv文件并不是很大,您可以尝试生成一个包含类似于print _("the value of the thing you want to translate")
的行的文件,这将被xgettext
所理解。当然,这不是最佳的方式,但它是最直接的,而不必担心解析。
import csv
import gettext
t = gettext.translation('api_trans', '/path/to/locale/', fallback=True)
_ = t.ugettext
string_list = []
with open('/path/to/csv/file') as csvfile:
with open('/path/to/some/other/file', 'w') as out:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in reader:
if row:
if row[0] != '':
out.write("print _(%s)\n" % (repr(row[0],))
然后你会执行xgettext -d api_trans -o api_trans.pot /path/to/that/file
。
再次,这是次优。你可能想看看Babel,并提出一个更有效的解决方案,我也会研究。
这就是我使用了巴贝尔:
def extract_csv(fileobj, keywords, comment_tags, options):
"""Extract messages from XXX files.
:param fileobj: the file-like object the messages should be extracted
from
:param keywords: a list of keywords (i.e. function names) that should
be recognized as translation functions
:param comment_tags: a list of translator tags to search for and
include in the results
:param options: a dictionary of additional options (optional)
:return: an iterator over ``(lineno, funcname, message, comments)``
tuples
:rtype: ``iterator``
"""
import csv
reader = csv.reader(fileobj, delimiter=',', quotechar='"')
for row in reader:
if row and row[0] != '':
yield (lineno, ',', row[0], 'No comment')
那么你就需要将它作为一种提取方法。最简单的方法就是把它在一个包中PYTHONPATH
并使用它,如下所示:
# Some custom extraction method
[extractors]
csv = mypackage.module:extract_csv
[csv: **.ctm]
some_option = foo
我不能完全肯定这最后一点,你可以看到here更多细节:)
谢谢您!这将做到这一点。我不走Babel路线的原因是,文档有点含糊,有些关键点,而不是花时间尝试将消息提取与Babel合并,我正在尝试这种方法,因为正如你猜测的那样,这是一个很小的需要翻译的作品清单。 – deecodameeko
@deecodameeko好吧!我和Babel在一起,但没有尝试过......所以我只是在这里更新以防万一你想试试:) – jadkik94
thanks @ jadkik94。你一直在帮助很大! – deecodameeko