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 function called HackCaesar with the following requirements: def hack_caesar(cyphertext): ‘’’ cyphertext is a...
Write a python function called HackCaesar with the following requirements: def hack_caesar(cyphertext): ‘’’ cyphertext is a text encoded using Caesars encryption. The encryption key is unknown. The function returns the correct encryption key. Hint: Use the function we wrote was called caesar(c, key) and could encode a single character. # YOUR CODE GOES HERE def is_odd(n): return n%2 == 1 def caesar(c, key): """ Encrypts a lower case character c using key Example: if c = "a" and key=3 then...
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’.
Python program please no def, main, functions Given a list of negative integers, write a Python...
Python program please no def, main, functions Given a list of negative integers, write a Python program to display each integer in the list that is evenly divisible by either 5 or 7. Also, print how many of those integers were found. Sample input/output: Enter a negative integer (0 or positive to end): 5 Number of integers evenly divisible by either 5 or 7: 0 Sample input/output: Enter a negative integer (0 or positive to end): -5 -5 is evenly...
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.
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' #...
Convert this code written in Python to Java: # Definition of a function isprime(). def isprime(num):...
Convert this code written in Python to Java: # Definition of a function isprime(). def isprime(num):     count=2;     flag=0;     # Loop to check the divisors of a number.     while(count<num and flag==0):         if(num%count!=0):             # Put flag=0 if the number has no divisor.             flag=0         else:             # Put flag=1 if the number has divisor.             flag=1         # Increment the count.         count=count+1     # Return flag value.     return flag # Intialize list. list=[]...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT