Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

How to put a textfile into sqlite simply using Python API?

I have a tab delimited file in the format:

sentenceID (sid) documentID (scid) sentenceText (sent)

E.g.

100004 100 即便您喜爱流连酒吧,也定然在这轻松安闲的一隅,来一场甜蜜沉醉的约会。
100005 100 您可以慢慢探究菜单上所有的秘密惊喜。

I want to put it into sqlite3 with the following schema:

CREATE TABLE sent (
 sid INTEGER PRIMARY KEY,
 scid INTEGER,
 sent TEXT,
 );

Is there a quick way to use the python API for sqlite (http://docs.python.org/2/library/sqlite3.html) to put them into a table?

I've been doing it as such:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
import sys, codecs
con = lite.connect('mycorpus.db')
with con: 
 cur = con.cursor()
 cur.execute("CREATE TABLE Corpus(sid INT, scid INT, sent TEXT, PRIMARY KEY (sid))")
 for line in codecs.read('corpus.tab','r','utf8'):
 sid,scid,sent = line.strip().split("\t")
 cur.execute("INSERT INTO Corpus VALUES("+sid+","+scid+"'"+sent+"')")

Answer*

Draft saved
Draft discarded
Cancel

default

AltStyle によって変換されたページ (->オリジナル) /