Python program to find the frequency of a particular word in a cell in an excel table

Welcome everyone,
This post is a treat for those, who wish to find the frequency of a particular word in a cell in an excel table, the code for it is very basic and simple. Therefore i did not find it fruitful to use a function, however, the user isn’t bound to stick this code and may implement methods if they deem it necessary.
(* note:┬áBefore you start penning the code down, make sure that you already have the ‘xlrd’ library installed in your computer. To install the ‘xlrd’ Run cmd as administrator and enter: “pip install xlrd”. If this doesn’t work, try googling for further solutions.

Finding Frequency of a word in a cell of an excel table: Python program

import xlrd

word=input("enter the word: ")
freq=0
path="Book1.xlsx"
wb=xlrd.open_workbook(path)
sheet=wb.sheet_by_index(0)
for i in range (sheet.nrows):
    for j in range (sheet.ncols):
        if(sheet.cell_value(i,j)==word):
            freq=freq+1

print(f"""The frequency of word: {word}
        is {freq}""")

Output :

1) enter the word: no
   The frequency of word: no
   is 2
2) enter the word: a
   The frequency of word: a
        is 0
3) enter the word: " "
   The frequency of word:" " 
        is 1
*note this is because i had an empty cell in my sheet.

Explanation :

The code begins by importing the xlrd library. The xlrd library from Pypi is a library that helps us to Deal with reading Excel files, more specifically .xls and .xlsx files.

The next step is taking the word whose frequency needs to be checked, from the user, thus we create a variable to store the frequency and initialize its value to zero.

We set the path of the excel file(You need to set the full-path of the file, unlike me). And then open the workbook by using the xlrd.open_workbook() command and passing the path as an argument in its parameters.

The next step is setting up the sheet, by using the sheet_by_index(), in my case which is 0. We then traverse through the excel table and keep searching if the value of the cell equals the value given by the user. If it does we iterate the value of the variable respectively.
In the end, we use a formatted string to print out the frequency.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *