发生这种情况的原因是,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,并提出更有效的解决方案,我也会研究一下。
这就是我使用 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 了解更多详情:)