Question

In: Computer Science

Python File program 5: Word Frequencies (Concordance)    20 pts 1. Use a text editor to create...

Python File

program 5: Word Frequencies (Concordance)    20 pts

1. Use a text editor to create a text file (ex: myPaper.txt) It should contain at least 2 paragraphs with around 200 or more words.

2. Write a Python program (HW19.py) that

  • asks the user to provide the name of the text file. Be SURE to check that it exists!
    Do NOT hard-code the name of the file! Use the entry provided by the user!
  • read from the text file
  • NOTE: (write your program so that it ONLY works if it reads from the file specified by the user).

3. Your program will produce a dictionary of words with the number of times each occurs. It maps a word to the number of times the word occurs

  • Key: a word
  • Value: the number of times the word occurs in the text. The report should be an ALPHABETIZED output table, listing the word and the number of occurrences.

NOTES:

  • The input sequence can be words, numbers or any other immutable Python object, suitable for a dict key.
  • Ignore case – apple is the same as Apple is the same as APPLE, etc.
  • Discard all punctuation and extra white space (newlines, tabs, blanks, etc.).
  • Put the words into a dictionary. The first time a word is seen, the frequency is 1. Each time the word is seen again, increment the frequency. NOTE: you are REQUIRED to use the dictionary class for this assignment.
  • Produce a frequency table. To alphabetize the frequency table, extract just the keys and sort them. This sorted sequence of keys can be used to extract the counts from the dict.
  • Make sure that your output (the table) is formatted so that the columns are aligned, and so that there are titles for each column.
  • Be sure to modularize your code, using functions appropriately.
  • The main function should be clean and easy to read, calling the functions with meaningful names. Pass parameters – do not use global variables.

BONUS +5 pts:

  • Create a menu-driven front-end to this application.
    • First, populate the dictionary from the file
    • Next, provide a menu that allows the user to
      • Add words to the dictionary
                after asking the user for the word to add
                Note: the count should increase if the word is already there)
      • Check if a word is already in the dictionary
      • Delete a word from the dictionary after asking the user for the word to delete
      • Print the dictionary entries in table form as described above.
  • Allow the user to continue using the menu until they choose the option to quit.

Solutions

Expert Solution

from os import path
import sys
def fileExists(fileName):
    a=path.isfile(fileName)
    if(a):
        return True
    else:
        return False
    
def readWords(fname):
    f = open(fname, "r")
    data = f.read()
    words=data.split()
    return words

def populateDictionary(words):
    d={}
    for i in words:
        d=addWordToDictionary(i, d)
    return d
def addWordToDictionary(i,d):
    punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    i=i.casefold()
    for p in i:
        if p in punctuations:
            i=i.replace(p,"")
    if i in d:
        d[i]=d[i]+1
    else:
        d[i]=1
    return d
    
def checkDictionary(i,d):
    i=i.casefold()
    if i in d:
        return True
    else:
        return False
def deleteWordInDictionary(i,d):
    e=checkDictionary(i, d)
    if(e):
        d.pop(i)
        return True
    else:
        return False

def printDictionary(d):
    print("{:<15} {:<15}".format("Word","Frequency"))
    for i in sorted(d):
        print("{:<15} {:<15}".format(i,d[i]))

def menu(s):
    if(int(s)==1):
        print("Enter the word to add to the dictionary:")
        r=input()
        addWordToDictionary(r, d1)
        print("After adding word to dictionary:")
        printDictionary(d1)
    elif(int(s)==2):
        print("Enter the word to check")
        c=input()
        c1=checkDictionary(c, d1)
        if(c1):
            print("The word exists in the dictionary")
        else:
            print("The word does not exists in the dictionary")
            
    elif(int(s)==3):
        print("Enter the word to delete from dictionary:")
        d2=input()
        q3=deleteWordInDictionary(d2,d1)
        if(q3):
            print("The word ",d2," is deleted from the dictionary")
            print("After deleting word from dictionary:")
            printDictionary(d1)
        else:
            print("The word does not exists in the dictionary.So it cannot be deleted")
    elif(int(s)==4):
        printDictionary(d1)
    elif(int(s)==5):
        sys.exit()
    else:
        print("Enter the valid option")
    
fname = input("Please enter the input file with extension: ")   
f=fileExists(fname)
if(f):
    words=readWords(fname)
    d1=populateDictionary(words)
    print("The frequency of words is ")
    printDictionary(d1)
    print("\nMENU\n")
    print("1.Add word to dictionary\n2.Check whether the word is already in the dictionary \n3.Delete the word from dictionary\n",
          "4.Print the entries in table form\n5.Quit the program\n Enter your option")
    s=input()
    while(s):
        menu(s)
        print("1.Add word to dictionary\n2.Check whether the word is already in the dictionary \n3.Delete the word from dictionary\n",
          "4.Print the entries in table form\n5.Quit the program\n Enter your option")
        s=input()
else:
    print("The entered file does not exists")
    
    
    

Screenshot of the code:

myPaper.txt file:

                All of us, at least once in our lives, have experienced our parents hollering at us for sitting idle. 
When they see us roaming around unnecessarily or sitting without any work, they seemingly ask don't we have better things to do? 
We always take it as unneeded screaming and fail to realize the deeper meaning it holds. Life spent doing constructive work, is life well spent. 
The great dramatist Shakespeare rightly observed that life should be measured by deeds, not years. Age is no criterion for the meaning of life. 
It is the actions, good deeds which give meaning to life and make man immortal. Long life is desired by all, but if one does not do any noble deeds,
 then such a life has no worth. Great leaders like Mahatma Gandhi, Lal Bahadur Shastri, Abraham Lincoln, Swami Vivekananda, Mother Teresa and many others
  are remembered even after so many years after their passing. People still take inspiration from their lifestyles and preachings. 
  It is only the great deeds of these leaders that have inspired many generations. 
                  A lily flower lives just for a day, but it is remembered for its fragrance and sweetness. 
Respect is earned by actions and not acquired by years. Existence becomes exciting when it is lived for others or when it does something beneficial 
to mankind. We generally work for the whole day, earn money and spend it on our needs. These are some common things that all do, but we should all do 
some noble deeds as well. We should share our smile, advice, cheer, and help with our fellow beings. These things may give them happiness and they may 
remember us when we are not around. Hence the saying, "We live in deeds, not in years," proves to be true.

Screenshot:

Screenshot of the output:


Related Solutions

Python: Word Frequencies (Concordance) 1. Use a text editor to create a text file (ex: myPaper.txt)...
Python: Word Frequencies (Concordance) 1. Use a text editor to create a text file (ex: myPaper.txt) It should contain at least 2 paragraphs with around 200 or more words. 2. Write a Python program (HW19.py) that asks the user to provide the name of the text file. Be SURE to check that it exists! Do NOT hard-code the name of the file! Use the entry provided by the user! read from the text file NOTE: (write your program so that...
Word Frequencies (Concordance)    1. Use a text editor to create a text file (ex: myPaper.txt)...
Word Frequencies (Concordance)    1. Use a text editor to create a text file (ex: myPaper.txt) It should contain at least 2 paragraphs with around 200 or more words. 2. Write a Python program (HW19.py) that asks the user to provide the name of the text file. Be SURE to check that it exists! Do NOT hard-code the name of the file! Use the entry provided by the user! read from the text file NOTE: (write your program so that...
In Python. A file concordance tracks the unique words in a file and their frequencies. Write...
In Python. A file concordance tracks the unique words in a file and their frequencies. Write a program that displays a concordance for a file. The program should output the unique words and their frequencies in alphabetical order. Variations are to track sequences of two words and their frequencies, or n words and their frequencies. Below is an example file along with the program input and output: Input : test.txt output : 3/4 1, 98 1, AND 2, GUARANTEED 1,...
A file concordance tracks the unique words in a file and their frequencies. Write a program...
A file concordance tracks the unique words in a file and their frequencies. Write a program that displays a concordance for a file. The program should output the unique words and their frequencies in alphabetical order. Variations are to track sequences of two words and their frequencies, or n words and their frequencies.
Use Vi text editor or ATOM to create a bash script file. Use the file name...
Use Vi text editor or ATOM to create a bash script file. Use the file name ayaan.sh. The script when ran it will execute the following commands all at once as script. Test your script file make sure it works. Here is the list of actions the script will do: It will create the following directory structure data2/new2/mondaynews off your home directory. inside the mondaynews, create 4 files sports.txt, baseball.txt, file1.txt and file2.txt. Make sure file1.txt and file2.txt are hidden...
In linux , Using a simple text editor, create a text file with the following name...
In linux , Using a simple text editor, create a text file with the following name &quot;Test&quot; and content: GNU GENERAL PUBLIC LICENSE The GNU General Public License is a free, copy left license for the GNU General Public License is intended to guarantee your freedom to GNU General Public License for most of our software; it applies … 2-Write the command to create the text file. 3-Print the file permissions. 4-Create a directory named &quot;361&quot; 5-Copy file &quot;Test&quot; to...
Write a program that creates a concordance. There will be two ways to create a concordance. The first requires a document to be read from an input file, and the concordance data is written to an output file.
Concepts tested by this program            Hash Table,            Link List,hash code, buckets/chaining,exception handling, read/write files (FileChooser)A concordance lists every word that occurs in a document in alphabetical order, and for each word it gives the line number of every line in the document where the word occurs.Write a program that creates a concordance. There will be two ways to create a concordance. The first requires a document to be read from an input file, and the concordance data is written to...
language: python Create a text file in your project folder with at least 20 "quirky sayings"/fortunes...
language: python Create a text file in your project folder with at least 20 "quirky sayings"/fortunes (the only requirement is that they be appropriate for display in class), If I use my own file though, you should handle as many fortunes as I put in. Make each fortune its own line, •in your main function ask the user for the name of the fortunes file.•Create a function which takes the name of the fortunes file as a parameter, open that...
I have a Python code that reads the text file, creates word list then calculates word...
I have a Python code that reads the text file, creates word list then calculates word frequency of each word. Please see below: #Open file f = open('example.txt', 'r') #list created with all words data=f.read().lower() list1=data.split() #empty dictionary d={} # Adding all elements of the list to a dictionary and assigning it's value as zero for i in set(list1):     d[i]=0 # checking and counting the values for i in list1:     for j in d.keys():        if i==j:           d[i]=d[i]+1 #Return all non-overlapping...
Write a C++ program to create a text file. Your file should contain the following text:...
Write a C++ program to create a text file. Your file should contain the following text: Batch files are text files created by programmer. The file is written in notepad. Creating a text file and writing to it by using fstream: to write to a file, you need to open thew file as write mode. To do so, include a header filr to your program. Create an object of type fsrteam. Open the file as write mode. Reading from a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT