我有一个csv包含要翻译的所有值...我想读取csv文件并生成.pot文件,但是当我加载并尝试调用print _(value)时,没有.pot生成。不确定为什么你不能用csv生成带有动态内容的.pot文件。
以下是我的代码片段:
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:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in reader:
if row:
if row[0] != '':
print _(%row[0])
当我运行此脚本时,我会看到列出的所有值,但是如果我运行则不会生成.pot文件:
xgettext -d api_trans -o api_trans.pot api_trans.py
指定一个实际字符串与一个带字符串值的变量(例如print _('hello'))确实有效......任何帮助都将非常感激。
答案 0 :(得分:0)
发生这种情况的原因是因为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了解更多详情:)