Ask Question
7 August, 16:05

Write a program that reads the contents of a text file. The program should create a dictionary in which the keys are the individual words found in the file and the values are the number of times each word appears. For example, if the word "the" appears 128 times, the dictionary would contain an element with 'the' as the key and 128 as the value. The program should either display the frequency of each word or create a second file containing a list of each word and its frequency.

+1
Answers (1)
  1. 7 August, 16:20
    0
    '''

    This is script makes use of dictionaries to get all the words in a file and the

    number of times they occur.

    '''

    #section 1

    import string

    dic = {}

    textFile=open ("Text. txt","r")

    # Iterate over each line in the file

    for line in textFile. readlines ():

    tex = line

    tex = tex. lower ()

    tex=tex. translate (str. maketrans ('', '', string. punctuation)) #removes every punctuation

    #section 2

    new = tex. split ()

    for word in new:

    if word not in dic. keys ():

    dic[word] = 1

    else:

    dic[word] = dic[word] + 1

    for word in sorted (dic):

    print (word, dic[word], '/n')

    textFile. close ()

    Explanation:

    The programming language used is python.

    #section 1

    The string module is imported because of the string operations that need o be performed. Also, an empty list is created to hold the words and the number of times that they occur and the file is opened in the read mode, because no new content is going to be added to the file.

    A FOR loop is used to iterate through every line in the file and assigns each line to a variable one at a time, and each line is converted to lowercase and punctuation is stripped off every word in each line.

    This processing is needed in order for the program o accurately deliver the number of occurrences for each individual word in the text.

    #section 2

    Each line is converted to a list using the split function, this is done so that a FOR loop can iterate over each word. The FOR loop, iterates over each word in the list and the IF statement checks if the word is already in the dictionary, if the word id in the dictionary, it increases the number of occurrences, if it is not in the dictionary, it adds it to the dictionary and assigns the number 1 to it.

    The words are then sorted just to make it look more organised and the words and the number of times that they occur is printed to the screen.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a program that reads the contents of a text file. The program should create a dictionary in which the keys are the individual words ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers