|
| 1 | +import sqlite3 |
| 2 | + |
| 3 | +# create a connection object that represents the database, the data will be stored in the emaildb.sqlite file. |
| 4 | +conn = sqlite3.connect('emaildb.sqlite') |
| 5 | + |
| 6 | +# create a cursor object and call execute() method to perform SQL commands |
| 7 | +cur = conn.cursor() |
| 8 | + |
| 9 | +# every time run this program, drop the table and then create it again |
| 10 | +cur.execute(''' |
| 11 | +DROP TABLE IF EXISTS Counts''') |
| 12 | +cur.execute(''' |
| 13 | +CREATE TABLE Counts (org TEXT, count INTEGER)''') |
| 14 | + |
| 15 | +# prompt for file name |
| 16 | +fname = raw_input('Enter file name: ') |
| 17 | +if ( len(fname) < 1 ) : fname = 'mbox-short.txt' |
| 18 | +fh = open(fname) |
| 19 | +for line in fh: |
| 20 | + if not line.startswith('From: ') : continue |
| 21 | + pieces = line.split() |
| 22 | + email = pieces[1] |
| 23 | + parts = email.split('@') |
| 24 | + org = parts[1] |
| 25 | + print org |
| 26 | + # question maker is a place holder to be filled in |
| 27 | + cur.execute('SELECT count FROM Counts WHERE org = ? ', (org, )) |
| 28 | + row = cur.fetchone() |
| 29 | + if row is None: |
| 30 | + cur.execute('''INSERT INTO Counts (org, count) |
| 31 | + VALUES ( ?, 1 )''', ( org, ) ) |
| 32 | + else : |
| 33 | + cur.execute('UPDATE Counts SET count=count+1 WHERE org = ?', |
| 34 | + (org, )) |
| 35 | + # This statement commits outstanding changes to disk each |
| 36 | + # time through the loop - the program can be made faster |
| 37 | + # by moving the commit so it runs only after the loop completes |
| 38 | + conn.commit() |
| 39 | + |
| 40 | +# https://www.sqlite.org/lang_select.html |
| 41 | +sqlstr = 'SELECT org, count FROM Counts ORDER BY count DESC LIMIT 10' |
| 42 | + |
| 43 | +print |
| 44 | +print "Counts:" |
| 45 | +for row in cur.execute(sqlstr) : |
| 46 | + print str(row[0]), row[1] |
| 47 | + |
| 48 | +cur.close() |
| 49 | + |
| 50 | + |
| 51 | +# https://docs.python.org/2/library/sqlite3.html |
0 commit comments