-
Notifications
You must be signed in to change notification settings - Fork 45
/
db.py
executable file
·103 lines (83 loc) · 2.29 KB
/
db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import sqlite3
'''
create table word(word, doctype, count);
create table doctype_count(doctype, count);
create index i1 on word(word, doctype);
delete from word;
update ad_count set count = 0;
'''
class Db:
def __init__(self):
self.conn = sqlite3.connect('./bayes.db')
def reset(self):
c = self.conn.cursor()
try:
c.execute('delete from word')
c.execute('delete from doctype_count')
finally:
c.close()
self.conn.commit()
def update_word_count(self, c, doctype, word, num_to_add_to_count):
c.execute('select count from word where doctype=? and word=?', (doctype, word))
r = c.fetchone()
if r:
c.execute('update word set count=? where doctype=? and word=?', (r[0] + num_to_add_to_count, doctype, word))
else:
c.execute('insert into word (doctype, word, count) values (?,?,?)', (doctype, word, num_to_add_to_count))
def update_word_counts(self, d, doctype):
c = self.conn.cursor()
try:
for word, count in d.items():
self.update_word_count(c, doctype, word, count)
finally:
c.close()
self.conn.commit()
def get_doctype_counts(self):
counts = {}
c = self.conn.cursor()
try:
for row in c.execute('select doctype, count from doctype_count'):
counts[row[0]] = row[1]
return counts
finally:
c.close()
self.conn.commit()
def get_word_count(self, doctype, word):
c = self.conn.cursor()
try:
c.execute('select count from word where doctype=? and word=?', (doctype, word))
r = c.fetchone()
if r:
return r[0]
else:
return 0
finally:
c.close()
self.conn.commit()
def get_words_count(self, doctype):
c = self.conn.cursor()
try:
c.execute('select sum(count) from word where doctype=?', (doctype, ))
r = c.fetchone()
if r:
return r[0]
else:
return 0
finally:
c.close()
self.conn.commit()
def update_doctype_count(self, num_new_ads, doctype):
c = self.conn.cursor()
try:
counts = self.get_doctype_counts()
if counts.has_key(doctype):
current_count = counts[doctype]
else:
current_count = 0
if current_count:
c.execute('update doctype_count set count=? where doctype=?', (current_count + num_new_ads, doctype))
else:
c.execute('insert into doctype_count (doctype, count) values (?, ?)', (doctype, num_new_ads))
finally:
c.close()
self.conn.commit()