Welcome folks today in this blog post we will be counting words in sentences
using collections and tkinter in python. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
#Imports import tkinter as tk from tkinter import * from collections import Counter #Functions def countWords(s): signos = [',', '.', ';', ':'] cleanstr = '' for letra in s.lower(): if letra in signos: cleanstr += '' else: cleanstr += letra strlist = cleanstr.split(' ') return dict(Counter(strlist)) def button_count(): text = mainWindow.e2.get() count = countWords(text) myLabel = Label(root, text=count) myLabel.pack() #Graphics root = tk.Tk() root.title("Count words") root.geometry('400x400') #Class Window class Window: def __init__(self, root): self.root = root self.e2 = tk.StringVar() self.e = tk.Entry(root, textvariable=self.e2, width=35, borderwidth=5) self.e.pack() self.button = Button(root, text="Count words", command=button_count) self.button.pack() self.exit_button = Button(root, text="Exit", command=root.quit) self.exit_button.pack() if __name__ == '__main__': mainWindow = Window(root) root.mainloop() |
Now if you execute the python
script by typing the below command as shown below
python app.py