Question

In: Computer Science

Python 3 Program Program 4 should first tell users that this is a word analysis software....

Python 3 Program

Program 4 should first tell users that this is a word analysis software. For any user-given text file, the program will read, analyze, and write each word with the line numbers where the word is found in an output file. A word may appear in multiple lines. A word shows more than once at a line, the line number will be only recorded one time.

Ask a user to enter the name of a text file. Using try/except for invalid user input. Then the program reads the contents of the text file and create a dictionary in which the key-value pairs are described as follows:

Key. The key are the individual words found in the file.

Value. Each value is a list that contains the line numbers in the file where the word (the key) is found. Be aware that a list may have only one element.

Once the dictionary has been built, the program should create another text file for otuput, named “words_index.txt”. Next, write the contents of the dictionary to the file as an alphabetical listing of the words that are stored as keys in the dictionary (sorting the keys), along with the line numbers where the words appear in the original file. Please see the sample file for your reference.

Looking to seeing everyone to submit a well-done program! Here are some tips:

Documents/Comments of your program (Never more)

Testing your program by the given two files, Kennedy.txt . The output file of the Kennedy_index.txt, Kennedy_index_B.txt, Kennedy_index_C.txt, for input file “kennedy.txt”

Remember the output file name of your program is words_index.txt.

For this program, not running one (syntax error) will receive NO point.

Example of original text- Kennedy.txt

We observe today not a victory
of party but a celebration
of freedom symbolizing an end
as well as a beginning
signifying renewal as well
as change

New text example - Kennedy_index.txt

Text File to be analyzed: Kennedy.txt

We: 1
a: 1, 2, 4
an: 3
as: 4, 5, 6
beginning: 4
but: 2
celebration: 2
change: 6
end: 3
freedom: 3
not: 1
observe: 1
of: 2, 3
party: 2
renewal: 5
signifying: 5
symbolizing: 3
today: 1
victory: 1
well: 4, 5

example- Kenndy_index_B.txt

Text File to be analyzed: kennedy.txt

          We : 1
           a : 1, 2, 4
          an : 3
          as : 4, 5, 6
   beginning : 4
         but : 2
 celebration : 2
      change : 6
         end : 3
     freedom : 3
         not : 1
     observe : 1
          of : 2, 3
       party : 2
     renewal : 5
  signifying : 5
 symbolizing : 3
       today : 1
     victory : 1
        well : 4, 5

example- Kenndy_index_C.txt

Text File to be analyzed: kennedy.txt

We           : 1
a            : 1, 2, 4
an           : 3
as           : 4, 5, 6
beginning    : 4
but          : 2
celebration  : 2
change       : 6
end          : 3
freedom      : 3
not          : 1
observe      : 1
of           : 2, 3
party        : 2
renewal      : 5
signifying   : 5
symbolizing  : 3
today        : 1
victory      : 1
well         : 4, 5

Solutions

Expert Solution

Thanks for the question.

Below is the code you will be needing  Let me know if you have any doubts or if you need anything to change.

Thank You !

Please update the below two lines -
filename = 'Kennedy.txt'
output_filename='words_index.txt'
===========================================================================

def read_file(filename):
    try:
        with open(filename, 'r') as infile:
            word_line_dict = {}
            line_number = 1
            for line in infile.readlines():
                for word in line.strip().split():
                    if word in word_line_dict.keys():
                        lines_list = word_line_dict.get(word)
                        lines_list.append(line_number)
                    else:
                        lines_list = [line_number]
                        word_line_dict[word] = lines_list
                line_number += 1
        return word_line_dict
    except:
        return None


def write_to_file(filename, word_dict):
    with open(filename, 'w+') as outfile:

        for word in sorted(word_dict.keys()):
            lines=word_dict.get(word)
            lines.sort()
            outfile.write('{}: {}\n'.format(word, ','.join([str(l) for l in lines])))


def main():
    filename = 'Kennedy.txt'
    word_dict = read_file(filename)
    if word_dict is None:
        print('Error: File could not be read or file not available')
        return
    print(word_dict)
    output_filename='words_index.txt'
    write_to_file(output_filename,word_dict)

main()

=======================================================================


Related Solutions

python: Write a program that turns a sentence into camel case. The first word is lowercase,...
python: Write a program that turns a sentence into camel case. The first word is lowercase, the rest of the words have their initial letter capitalized, and all of the words are joined together. For example, with the input "fOnt proCESSOR and ParsER", your program will output "fontProcessorAndParser". Optional: can you do this with a list comprehension? Optional extra question: print a warning message if the input will not produce a valid variable name. You don't need to be exhaustive...
I'm making a python program that checks the users input. If the users input does not...
I'm making a python program that checks the users input. If the users input does not match the rules then the program will output "No". If the users input does match the rules it will output "Yes". The rules are : at least 5 uppercase letters at least 5 lowercase letters at least 5 numbers No more than 20 characters in total I have managed to meet these conditions in individual python files but not in one. Ideally without importing...
I'm making a python program that checks the users input. If the users input does not...
I'm making a python program that checks the users input. If the users input does not match the rules then the program will output "No". If the users input does match the rules it will output "Yes". The rules are : 5 uppercase letters 5 lowercase letters 5 numbers First letter must be capitilized The total characters must be 15 I have managed to meet these conditions in individual python files but not in one. Ideally without importing anything, still...
PYTHON In this lab we will design a menu-based program. The program will allow users to...
PYTHON In this lab we will design a menu-based program. The program will allow users to decide if they want to convert a binary number to base 10 (decimal) or convert a decimal number to base 2 (binary). It should have four functions menu(), reverse(), base2(), and base10(). Each will be outlined in detail below. A rubric will be included at the bottom of this document. Menu() The goal of menu() is to be the function that orchestrates the flow...
For each of the following propositions the first word in your answer should be the word...
For each of the following propositions the first word in your answer should be the word True or the word False followed by a brief explanation as to why the proposition is true or false. assume that Frank and Athena can produce either chairs or tables. If Athena has a comparative advantage in producing chairs, then she would be able to sell chairs for a higher price than Frank.
Late in the year, Software City began carrying WordCrafter, a new word processing software program. At...
Late in the year, Software City began carrying WordCrafter, a new word processing software program. At December 31, Software City’s perpetual inventory records included the following cost layers in its inventory of WordCrafter programs. Purchase Date Quantity Unit Cost Total Cost Nov. 14 10 $ 410 $ 4,100 Dec. 12 24 $ 330 7,920 Total available for sale at Dec. 31 34 $ 12,020 a. At December 31, Software City takes a physical inventory and finds that all 34 units...
Write a Python program that will ask the user to input a word, will return the...
Write a Python program that will ask the user to input a word, will return the first letter of the input word, and ask the user to put another word, and so on, in the form of a loop. If the user chooses to stop, he or she should input the integer "0" for the loop to stop.
MATLAB Program a Matlab version of Guess the Word. The word should be determined by user...
MATLAB Program a Matlab version of Guess the Word. The word should be determined by user input. Once the word is determined, the game should begin by displaying blanks (-) where all the letters of the word are. The game should then continue to prompt the player to guess a letter in the word. If the player guesses a letter that is in the word and not already displayed, that letter should be displayed everywhere it appears in the word....
Write a Python 3 program called “parse.py” using the template for a Python program that we...
Write a Python 3 program called “parse.py” using the template for a Python program that we covered in this module. Note: Use this mod7.txt input file. Name your output file “output.txt”. Build your program using a main function and at least one other function. Give your input and output file names as command line arguments. Your program will read the input file, and will output the following information to the output file as well as printing it to the screen:...
I need to write a program in python for a restaurant. The program should let the...
I need to write a program in python for a restaurant. The program should let the user enter a meal number, then it should display the meal name, meal price, and meal calories. Also, needs the appropriate output if the user enters an invalid meal number. I am supposed to use a dictionary, but my problem is it keeps giving me an error and telling me my menu is not defined. Not sure what I am doing wrong. print ("Welcome...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT