我使用python对文件进行了一些操作。现在我只需要创建一个包含两列的表...一个用于msgid,另一个用于msgstr ...所有msgid
应存储在msgid
列中,并且所有{{1 s应存储在msgstr
列..
我对编程世界很陌生。请帮助我。我粘贴了我在下面所做的事情:
msgstr
答案 0 :(得分:1)
这有两个部分:
msgid
和相应的msgstr
值
.po文件。msgid
和msgstr
插入SQLite中的表格中
数据库中。对于第1部分,我建议使用babel
模块。您可以使用
pip install babel
使用babel.messages.pofile.read_po()
功能阅读.po
文件。这将返回一个目录,您可以在该目录上迭代从文件解析的所有消息:
from babel.messages.pofile import read_po
with open('ru.po') as po_file:
cat = read_po(po_file)
for message in cat:
if message.id:
print '{!r} -> {!r}'.format(message.id, message.string)
第2部分:
import sqlite3
conn = sqlite3.connect('catalog.db')
cursor = conn.cursor()
result = cursor.execute('CREATE TABLE ru (msgid TEXT, msgstr TEXT)')
# bulk insert the messages
messages = [(msg.id, msg.string) for msg in cat if msg.id]
result = cursor.executemany('INSERT INTO ru (msgid, msgstr) VALUES (?, ?)', messages)
assert(result.rowcount == len(messages))
conn.commit()
result = cursor.execute("SELECT * from ru where msgid = '11 inches/sec.'")
msgid, msgstr = result.fetchone()
# .encode('utf8') can be removed for Python 3
print '"{}" translates to "{}"'.format(msgid, msgstr.encode('utf8'))
msgid = 'A Samba password is required to export printer drivers'
result = cursor.execute("SELECT * from ru where msgid = ?", (msgid,))
msgid, msgstr = result.fetchone()
print '"{}" translates to "{}"'.format(msgid, msgstr.encode('utf8'))
<强>输出强>
"11 inches/sec." translates to "11 дюймов/с" "A Samba password is required to export printer drivers" translates to "Для экспорта драйверов принтера требуется пароль Samba"
你可能会注意到有很多msgid
个空msgstr
个。如果您不想要它们,请修改
messages = [(msg.id, msg.string) for msg in cat if msg.id]
到
messages = [(msg.id, msg.string) for msg in cat if msg.id and msg.string]