Searching Within a Text - The Advantages of Learning Python Programming for Beginners: A Comprehensive Guide

Latest

Dive into the world of Python programming with our comprehensive resources

Music

logo

Thursday, March 2, 2023

Searching Within a Text

 

In this article, we are reading from the txt file and  inputting contents into a Entry. We enter the word to be searched in the other Entry. By clicking the button, we search within the text in the Entry.

 


 

 

 

 

 

 

 

 Figure 1

 



 

 

 

 

 

 

 Figure 2

 

from tkinter import *

 

root = Tk()

root.title("text to find..bs")

 

frame = Frame(root)

 

#adding label to search box.

Label(frame,text='Text to find (Metin icerisinde bul) :',font=("Arial,12,bold")).pack(side=LEFT)

 

#adding of single line text box

edit = Entry(frame,font=("Arial,12,bold"))

 

#positioning of text box.

edit.pack(side=LEFT, fill=BOTH, expand=1)

 

#setting focus.

edit.focus_set()

 

#adding of search button.

btn = Button(frame, text='Search',font=("Arial,12,bold"),width=15,height=1,pady=3,fg='white', bg='deepskyblue')

btn.pack(side=RIGHT)

frame.pack(side=TOP)

 

#text box in root window.

text = Text(root,font=("Arial,12,bold"),fg='black', bg='lightyellow')

 

 

#reading a .txt and inputting contents into a textbox.

with open("D:\\person.txt", 'r') as passtxt:

        content = passtxt.read().strip()

        if content != "":

         text.insert('1.0',content)

        else:

         #text input area at index 1 in text window.

         text.insert('1.0','''Type your text here..Buraya aranacak metini yaziniz..''')

 

text.pack(side=BOTTOM)

 

 

#function to search string in text.

def find():

    

    #remove tag 'found' from index 1 to END.

    text.tag_remove('found', '1.0', END)

    

    #returns to widget currently in focus.. focus daki widgete donulur..

    s = edit.get()

    if s:

        idx = '1.0'

        while 1:

            #searches for desired string from index 1.

            idx = text.search(s, idx, nocase=1,

                              stopindex=END)

            if not idx: break

            

            #last index sum of current index and

            #length of text.

            lastidx = '%s+%dc' % (idx, len(s))

            

            #overwrite 'Found' at idx.

            text.tag_add('found', idx, lastidx)

            idx = lastidx

        

        #mark located string as red.

        text.tag_config('found', foreground='red')

    edit.focus_set()

btn.config(command=find)

 

root.mainloop()

 

 

Thank you. Happy coding.

No comments:

Post a Comment

Featured post

Python Introduction

What is Python? Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built ...