我有django项目,它有四种语言:
LANGUAGES = (
('en', _('English')),
('ru', _('Russian')),
('fr', _('French')),
('de', _('Deutsch')),
)
LOCALE_PATHS = (
BASE_DIR + '/locales',
)
所以,我在文件夹中有四个不同的文件“django.po”./locales/ [lang_symbol] /LC_MESSAGES/django.po
msgid和msgstr经常有多行。
我想创建csv文件以获取所有msgstr,并将它们从“en”文件分配给msgid,如下所示:
"msgid";"en";"ru";"fr";"de"
"contact";"";"Контакт","contact";"kontakt"
[etc]
我必须从这个文件创建一个包含所有翻译的文档,每行一个。怎么做?
答案 0 :(得分:1)
您可以使用polib来解析.po文件。这是应该完成工作的脚本,或者让您开始自定义。
import csv
from collections import OrderedDict
import polib
path_template = 'locales/{}/LC_MESSAGES/django.po'
# Hardcoded codes version.
langs = ['en', 'ru', 'fr', 'de',]
# You can use settings.LANGUAGES version for more versatility.
# Just remember that default i18n language (LANG_CODE) might not be the first on list of LANGUAGES in your project so msgid might be wrong in that case.
#langs = [lang[0] for lang in settings.LANGUAGES]
rows = OrderedDict()
rows['header'] = ['msgid'] + langs
for lang_code in langs:
po_path = path_template.format(lang_code)
po = polib.pofile(po_path)
for entry in po:
msgid = entry.msgid.encode('utf-8')
msgstr = entry.msgstr.encode('utf-8')
if msgid in rows.keys():
rows[msgid].append(msgstr)
else:
rows[msgid] = [msgid, msgstr]
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(rows.values())
从项目的根目录运行或更改用于满足您需求的文件的路径。
完整的1:1过渡可能需要进行一些调整,所以我要从头脑中提及。
entry
属性msgstr_plural
和msgid_plural
来访问它们。您提到的CSV格式可能仅限于存储多个复数形式。也不知道CSV最终目的。