You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
2.2 KiB
Python
78 lines
2.2 KiB
Python
import sqlite3
|
|
import random
|
|
|
|
|
|
def query(db, stmnt):
|
|
con = sqlite3.connect(db)
|
|
cur = con.cursor()
|
|
cur.execute(stmnt)
|
|
results = cur.fetchall()
|
|
con.close()
|
|
return results
|
|
|
|
|
|
def get_authors(db):
|
|
return query(db, 'SELECT * FROM Author ORDER BY lname')
|
|
|
|
|
|
def get_quotes(db):
|
|
stmnt = """SELECT qtext, fname, lname, source, qdate FROM Quote
|
|
NATURAL JOIN Author ORDER BY RANDOM()"""
|
|
return query(db, stmnt)
|
|
|
|
|
|
def format_quote(raw_quote):
|
|
"""
|
|
Return a tuple containing (text, source) for a quote given a raw quote
|
|
containing [text, author first name, author last name, source document,
|
|
quote date] where all fields accept text are possibly None values. Source
|
|
should be set to "Anonymous" if no other info is provided.
|
|
|
|
Examples:
|
|
|
|
>>> format_quote(['Quote', 'F', 'L', 'Source', 'Date'])
|
|
('Quote', 'F L, Source, Date')
|
|
>>> format_quote(['Quote', 'F', 'L', None, None])
|
|
('Quote', 'F L')
|
|
>>> format_quote(['Quote', 'F', 'L', 'Source', None])
|
|
('Quote', 'F L, Source')
|
|
>>> format_quote(['Quote', 'F', 'L', None, 'Date'])
|
|
('Quote', 'F L, Date')
|
|
>>> format_quote(['Quote', None, 'L', None, None])
|
|
('Quote', 'L')
|
|
>>> format_quote(['Quote', None, None, 'Source', None])
|
|
('Quote', 'Source')
|
|
>>> format_quote(['Quote', None, None, None, None])
|
|
('Quote', 'Anonymous')
|
|
"""
|
|
text = raw_quote[0]
|
|
source = []
|
|
|
|
# append author name (first and last) to source list if provided
|
|
if raw_quote[1] and raw_quote[2]:
|
|
source.append("%s %s" % (raw_quote[1], raw_quote[2]))
|
|
elif raw_quote[2]: # only last name provided
|
|
source.append(raw_quote[2])
|
|
|
|
# append source document and date to source list if provided
|
|
for item in raw_quote[-2:]:
|
|
if item:
|
|
source.append(item)
|
|
|
|
# join the pieces into a string seperated by comma and space
|
|
if source:
|
|
source = ", ".join(source)
|
|
else: # no source information provided, so make it "Anonymous"
|
|
source = "Anonymous"
|
|
|
|
return text, source
|
|
|
|
|
|
def get_random_quote(db):
|
|
return format_quote(get_quotes(db)[0])
|
|
|
|
|
|
if __name__ == '__main__':
|
|
import doctest
|
|
doctest.testmod()
|