2015-03-19 91 views
-1

我对使用python的文件进行了一些操作。现在我所要做的就是创建一个带有两列的表格...一个是用于msgid,另一个是用于msgstr ...所有msgid s应该存储在msgid列中,并且所有msgstr s应该存储在msgstr列中..使用python将文本文件存储到SQLite3数据库

我对编程世界很陌生。请帮助我。我已经贴了我必须做如下:

fn='ru.po' 
f=open(fn) 
output=[] 
for line in f: 
    if not '#' in line: 
     output.append(line) 
f.close() 
f=open(fn,'w') 
f.writelines(output) 
f.close 
+0

我想这可能是过于广泛,计算器一个问题。请查看python sqlite教程(例如http://zetcode.com/db/sqlitepythontutorial/)并询问您可能遇到的任何具体问题。 – lsowen 2015-03-19 12:31:24

+0

您想要将整个文件存储在数据库中或保存一个链接/路径吗? – Holloway 2015-03-19 12:32:32

+0

你的'.po'文件没有固有的结构,它还包含空白行和元数据。我可以猜测你想在数据库的表中存储“msgid”和“msgstr”作为列,但你需要更清晰地表达你的需求。 – mhawke 2015-03-19 12:36:34

回答

1

有由两个部分组成的:

  1. 从 .po文件解压缩msgid和相应的msgstr值。
  2. msgidmsgstr插入到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 s空msgstr s。如果你不想让他们,然后修改

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] 
+0

非常感谢! – kmg1 2015-03-19 15:10:19

相关问题