In: Computer Science
2. working with databases and files in python
a) Write a function with prototype “def profound():” that will prompt the user to type something profound. It will then record the date and time using the “datetime” module and then append the date, time and profound line to a file called “profound.txt”. Do only one line per function call. Use a single write and f-string such that the file contents look like:
2020-10-27 11:20:22 -- Has eighteen letters does
2020-10-27 11:20:36 -- something profound
b) Write a function with prototype “def bestwords():” that will prompt the user to enter a line with some of the best words (separated by spaces). These will be converted to lower case and stored in a data base file (using the dbm and pickle modules) whose keys are a tuple of the current year, month and day (using the datetime module) and the “values” are a set of words collected on that day. Each new word should be checked against all previously-entered words (even those on other days) and it is not added if it already exists in the database. (Hint: I simply subtracted all previous sets of words from the current set, then added that new set to the one for the current day (if it already existed).
c) Write a function with prototype “def printbestwords():” that will simply open the database of best words and print the keys and values, sorted by the keys. Don’t forget to close the database on exit. Example output:
(2020, 10, 26) {'infantroopen', 'susbesdig'}
(2020, 10, 27) {'deligitimatize'}
(2020, 10, 28) {'transpants', 'resaption'}
from datetime import datetime, date
import dbm, pickle
def profound():
# ask user for input
text = input('Type something profound: ')
#gets todays date and time
now = datetime.now()
# format date,time in required way
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
# opening the file in append mode, here a+ is used to create a new file if file doesnot exist
outputFile = open('profound.txt', 'a+')
# write into the file
outputFile.write(f'{formatted_date} -- {text}\n')
def bestwords():
# asks user for best words
bestWords = input('Enter some best words: ')
# opens the database in create mode
database = dbm.open('bestwords_data.db', 'c')
# getting the current date as tuple and pickilng it to get binary stream
currentDate = pickle.dumps((date.today().year, date.today().month, date.today().day))
# holds existing set of current day
existingSet = set()
# holds new words as a set
newSet = set(bestWords.lower().split())
# loads if existing set exists
try:
existingSet = pickle.loads(database[currentDate])
except KeyError:
pass
# writes the data in pickled form
database[currentDate] = pickle.dumps(existingSet.union(newSet))
# closes the database
database.close()
def printbestwords():
# opening the database in read mode
with dbm.open('bestwords_data.db', 'r') as database:
# looping through keys
for dateKey in database.keys():
# unpickle the current date to tuple, no need to sort since keys are in order
currentDate = pickle.loads(dateKey)
# unpickle the current wordset into set
currentWordSet = pickle.loads(database[dateKey])
# print currentdate and and current set
print(currentDate, currentWordSet)
profound()
bestwords()
printbestwords()
Code screenshot:
Output:
File(profound.txt):
PS: If you have any problems/doubts please comment below.Thank You