Tkinter Text小部件:搜索列表外的任何内容

时间:2016-07-18 15:47:36

标签: python list search text tkinter

在Python Tkinter中,如何将search函数放到Text小部件中,以便它只搜索给定列表之外的文本?

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()

如何在文本小部件中搜索不在列表中的单词。任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:1)

我不确定你想要做什么。如果您只想获得不在列表中的单词,只需使用text.get("1.0","end")获取文本小部件的内容,然后将其拆分为单词并检查每个单词是否在您的列表中。

编辑:如果你想要不在列表中的每个单词的第一个字母的索引,你可以做类似的事情

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

我假设在这个函数中,一行的开头永远不会有空格。