我有一个包含所有要转换的值的csv……我想读取csv文件并生成一个值文件,但当我加载并尝试调用.pot _( .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 指定实际字符串与具有字符串值的变量(例如,work...any _('hello'))是否提供打印帮助将非常感谢。
发布于 2013-01-08 04:56:49
发生这种情况的原因是因为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了解更多细节:)
https://stackoverflow.com/questions/14201517
复制相似问题