Advanced method - Program to count the number of words in a file using dictionaries

05 min read

Challenging task: Write a code to open a file and count the number of times each word has been repeated. Also, print the word with the maximum number of repetitions and the value of the number of times it has been repeated. (Using Dictionaries)

Solution: For such problems, using dictionaries would eliminate the process of solving the above problem with nested loops, which increase the complexity of the problem.   Now, we use an inbuilt function using dict.get() to get a new word as a new entry to the dict, if it's not already present in it and a key value of 1 is associated with it. If the word is available, then its associated key value is incremented by one.

The following is the code for the above-described problem,

name = input(' enter the file name')
handle = open(name)
counts = dict() #empty dict
for line in handle: # for every line in the file one by one
words = line.split() # split the line based on the spaces into different words
for word in words: # for each word in a line
counts[words] = counts.get(word,0)+1 # check if word exists, if yes increment count by 1, else add a new element into the dict with key value of 1

#check the count
bigword=None # initialise the variables
bigcount=None

for word,count in counts.items(): # this is one way of writing a for loop to iterate through the items in dictionary
if bigcount is None or count > bigcount: # check for the big count
bigword =word #print the bigword and big count
bigcount = count # here, we can extract all keys using dict.keys() function and find max of that list to directly find the bigcount value
print(bigword,bigcount)

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error