Make a Word Counter in Python Program ?

  Python Questions & Answers

Today we will read on this page – how we can create a word counter using Python.

We will use the partition function to make our work easier by reducing code length and increasing its productivity.

The split () function is a fairly useful and fairly common method for taking words out of a list. But this approach is applicable only as long as we avoid a particular character.

Example 1

#string on which the operation is to be performed
string_example = "All is well that ends well"
#printing original string
print("The original string is= " + string_example)
#using split
#counting words
res = len(string_example.split())
#printing the number of words
print("The number of words in the string are : " + str(res))

Result

The original string is= All is well that ends well
The number of words in the string are: 6

Example 2 – Creating a Word Counter GUI in Python

#import library
import tkinter as tk
#counting function
def charcount():
    output.delete(0.0,"end")
    w=inputUser.get(0.0,"end")
    sp=decision.get()
    c=0
#specifying conditions
    if sp==1:
        for k in w:
            if k=="\n":
                continue
            c=c+1
    elif sp==2:
        for k in w:
            if k==" " or k=="\n":
                continue
            c=c+1
    output.insert(tk.INSERT,c)
#creating interface
window=tk.Tk()
window.title("Count Characters")
window.geometry("500x600")
label=tk.Label(window,text="Input")
#Formatting
inputUser=tk.Text(window,width=450,height=10,font=("Helvetica",16),wrap="word")
decision=tk.IntVar()
#Radio buttons for space counting
r1=tk.Radiobutton(window,text="with spaces",value=1,variable=decision)
r2=tk.Radiobutton(window,text="without spaces",value=2,variable=decision)
#BUtton to count 
button=tk.Button(window,text="Count the number of characters",command=charcount)
label2=tk.Label(window,text="number of characters")
#Output Block
output=tk.Text(window,width=20,height=2,font=("Helvetica",16),wrap="word")
#Function calling
label.pack()
inputUser.pack()
r1.pack()
r2.pack()
label2.pack()
output.pack()
button.pack()
window.mainloop()

Result

Creating a Word Counter GUI in Python

Creating a Word Counter GUI in Python

 

LEAVE A COMMENT