mercredi 9 mars 2016

Inputting Python List into SQLite

Im trying to add the list that is made after it parses through each line.As I go through each code I get different errors and I know that it is bases I am not passing the correct data to the database but I cant figure this out on my own because I am a noob :(. Always best to ask right?

Any suggestions?

import sqlite
import re

conn = sqlite3.connect('emaildb.sqlite')
cur = conn.cursor()

cur.execute('''
DROP TABLE IF EXISTS Counts''')

cur.execute('''
CREATE TABLE Counts (email TEXT, count INTEGER)''')

fname = raw_input('Enter file name: ')
if ( len(fname) < 1 ) : fname = 'mbox-short.txt'
fh = open(fname)
for line in fh:
    if not line.startswith('From: ') : continue
    line = line.rstrip()
    email = re.findall('@(\S+[a-zA-Z]+)', line)
    print email
    cur.execute('SELECT count FROM Counts WHERE email = ? ', (email))
    row = cur.fetchone()
if row is None:
    #cur.execute('''INSERT INTO Counts (email, count) 
        #VALUES ( ?, 1 )''', ( email, ) )
else : 
    cur.execute('UPDATE Counts SET count=count+1 WHERE email = ?', 
        (email, ))
# This statement commits outstanding changes to disk each 
# time through the loop - the program can be made faster 
# by moving the commit so it runs only after the loop completes
conn.commit()

# http://ift.tt/1MjSvfC
sqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10'

print
print "Counts:"
for row in cur.execute(sqlstr) :
print str(row[0]), row[1]

cur.close()`

Aucun commentaire:

Enregistrer un commentaire