2015-03-19 87 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

相關問題