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.
Using Python C++ Purpose: Write and test a non-trivial 2-d array function. Write a user-defined function...
Using Python C++ Purpose: Write and test a non-trivial 2-d array function. Write a user-defined function that, given an arbitrary 2-d array as input, returns its perimeter sum, which is defined as the sum of all the elements along its perimeter. You must name your function perimeter_sum
Write functions in Python IDLE that do the following: i) A function that takes 2 arguments...
Write functions in Python IDLE that do the following: i) A function that takes 2 arguments and adds them. The result returned is the sum of the parameters. ii) A function that takes 2 arguments and returns the difference, iii) A function that calls both functions in i) and ii) and prints the product of the values returned by both.
Assignment Requirements Write a python application that consists of two .py files. One file is a...
Assignment Requirements Write a python application that consists of two .py files. One file is a module that contains functions used by the main program. NOTE: Please name your module file: asgn4_module.py The first function that is defined in the module is named is_field_blank and it receives a string and checks to see whether or not it is blank. If so, it returns True, if not it return false. The second function that is defined in the module is named...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT