python 使用数据库按计划对电子邮件进行计数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用数据库按计划对电子邮件进行计数相关的知识,希望对你有一定的参考价值。

import sqlite3

conn = sqlite3.connect('emaildb.sqlite') # create a database is not exist
cur = conn.cursor()

cur.execute('''
DROP TABLE IF EXISTS Counts''') # three quotes support multiple lines without \n

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

fname = raw_input('Enter file name: ') # raw_input to read from command line input
if ( len(fname) < 1 ) : fname = 'mbox.txt'
fh = open(fname)
for line in fh:
    if not line.startswith('From: ') : continue
    pieces = line.split()
    email = pieces[1]
    org = email.split('@')[1]
    print email
    print org
    
    cur.execute('SELECT count FROM Counts WHERE org = ? ', (org, ))
    row = cur.fetchone()
    if row is None:
        cur.execute('''INSERT INTO Counts (org, count) 
                VALUES ( ?, 1 )''', ( org, ) )
    else : 
        cur.execute('UPDATE Counts SET count=count+1 WHERE org = ?', 
            (org, ))
    # 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()

conn.commit()

# https://www.sqlite.org/lang_select.html
sqlstr = 'SELECT org, 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()

以上是关于python 使用数据库按计划对电子邮件进行计数的主要内容,如果未能解决你的问题,请参考以下文章

在 pandas / python 中对条件值进行分组和计数

[新星计划] Python内存管理 | 引用计数垃圾回收内存池机制

[新星计划] Python内存管理 | 引用计数垃圾回收内存池机制

[新星计划] Python内存管理 | 引用计数垃圾回收内存池机制

按键对python中的计数器进行排序

使用来自两列的数据进行计数[重复]