Question

In: Computer Science

2. working with databases and files in python a) Write a function with prototype “def profound():”...

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'}

Solutions

Expert Solution

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


Related Solutions

Write a Python function with prototype “def anagramdictionary(wordlist):” that will return an “anagram dictionary” of the...
Write a Python function with prototype “def anagramdictionary(wordlist):” that will return an “anagram dictionary” of the given wordlist  An anagram dictionary has each word with the letters sorted alphabetically creating a “key”.
In Python write a function with prototype “def dictsort(d):” which will return a list of key-value...
In Python write a function with prototype “def dictsort(d):” which will return a list of key-value pairs of the dictionary as tuples (key, value), reverse sorted by value (highest first) and where multiple keys with the same value appear alphabetically (lowest first).
Write a python program function to check the frequency of the words in text files. Make...
Write a python program function to check the frequency of the words in text files. Make sure to remove any punctuation and convert all words to lower case. If my text file is like this: Hello, This is Python Program? thAt chEcks% THE freQuency of the words! When is printed it should look like this: hello 1 this 1 is 1 python 1 program 1 that 1 checks 1 the 2 frequency 1 of 1 words 1
USING PYTHON 3.7 AND USING def functions. Write a function called GPA that calculates your grade...
USING PYTHON 3.7 AND USING def functions. Write a function called GPA that calculates your grade point average (GPA) on a scale of 0 to 4 where A = 4, B = 3, C = 2, D = 1, and F = 0. Your function should take as input two lists. One list contains the grades received in each course, and the second list contains the corresponding credit hours for each course. The output should be the calculated GPA. To...
Please answer using python 3 and def functions! Lab 2 Drill 3: (function practice) create and...
Please answer using python 3 and def functions! Lab 2 Drill 3: (function practice) create and use a function named highest() that takes three inputs and returns the highest number. After you have got it working, try calling the function with inputs ‘hat’, ‘cat’, ‘rat’.
In python def lambda_2(filename): # Complete this function to read grades from `filename` and map the...
In python def lambda_2(filename): # Complete this function to read grades from `filename` and map the test average to letter # grades using map and lambda. File has student_name, test1_score, test2_score, # test3_score, test4_score, test5_score. This function must use a lambda # function and map() function. # The input to the map function should be # a list of lines. Ex. ['student1,73,74,75,76,75', ...]. Output is a list of strings in the format # studentname: Letter Grade -- 'student1: C' #...
Function writing: 1). (1 point) Write the prototype of a value-returning function checkIfOdd. This function takes...
Function writing: 1). (1 point) Write the prototype of a value-returning function checkIfOdd. This function takes three integer parameters. It returns true if all three of the parameters are odd, and false otherwise. 2). (1 point) Write a sample call for this function. (Assume that you are calling from main) 3). (3 points) Write the definition (header and body) of the function.
PYTHON...... Working with lists, functions, and files Objective: Work with lists Work with lists in functions...
PYTHON...... Working with lists, functions, and files Objective: Work with lists Work with lists in functions Work with files Assignment: Part 1: Write a program to create a text file which contains a sequence of test scores. Ask for scores until the user enters an empty value. This will require you to have the scores until the user enters -1. After the scores have been entered, ask the user to enter a file name. If the user doesn’t not enter...
a python function that reads two text files and merges in to one Linked List, be...
a python function that reads two text files and merges in to one Linked List, be able to print each Item in the new single Linked List class Node(object): item = -1 next = None def __init__(self, item, next): self.item = item self.next = next ================================ textfile! 979 2744 5409 1364 4948 4994 5089 703 1994 4637 2228 4004 1088 2812 170 5179 2614 238 4523 4849 3592 3258 1951 3440 3977 1247 4076 1824 4759 4855 5430 347 974...
Write a program in Python that walks through a folder tree and searches for files with...
Write a program in Python that walks through a folder tree and searches for files with a certain file extension (such as .pdf or .jpg). Copy these files from whatever location they are in to a new folder. The user can enter an absolute path for the start folder, or if the user does not enter a folder, the current directory is used. Likewise, the user can enter extensions to copy but if the user does not enter an extension,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT