Hung Truong
Hung Truong

Reputation: 369

Tkinter Text widget: search for anything outside a list

In Python Tkinter, how can you put a search function to a Text widget so it searches only text outside a given list ?

from tkinter import *
root = Tk()

text = Text(root)
text.pack()

def searchForTextOutsideList(event):
    list=["bacon","ham","sandwich"]
    ... # How can I search the text widget for only words not in the list

root.mainloop()

How can I search the text widget for only words not in the list. Any help is highly appreciated!

Upvotes: 0

Views: 91

Answers (1)

j_4321
j_4321

Reputation: 16169

I'm not sure of what you want to do exactly. If you only want to get the words not in your list, just use text.get("1.0","end") to get the content of the Text widget, then split it in words and check if each word is in your list or not.

Edit: If you want the index of the first letter of each word not in the list you can do something like that

def indices(word_list):
    """ return the index of the first letter of each word 
        in the text widget which is not in word_list """
    lines = text.get("1.0", "end").split("\n")
    index = []
    for i, line in enumerate(lines):
        words = line.split()
        if words:
            if not words[0] in word_list:
                index.append("%i.0" % (i+1))
            for j in range(1, len(words)):
                if not words[j] in word_list:
                    index.append("%i.%i" % (i+1, 1 + len(" ".join(words[:j]))))
    return index

I assumed in this function that there is never a white space at the beginning of a line.

Upvotes: 1

Related Questions