I am working on a spellchecker for a tkinter text widget. I've got it working so that the user can select an incorrect word and replace all instances of the incorrect word in the text widget. However, if the word appears within another word, it will also replace it. I don't want this.
For example:
Say the user had the sentence:
Hello how ay you today
And they've miss spelt the word 'are' as 'ay', they could right-click on it to replace all instances or the word 'ay' with 'are'.
My problem is, the string 'ay' appears in 'today'. This mean that when the user right clicks on 'ay', it turns 'today' into 'todare' - replacing the 'ay' in 'today' with 'are'
To replace the word I am using the search function. I thought about checking to see if the characters either side of the miss spelt word were spaces, but I didn't know how to implement it. Here is my code below (note - this is vastly simplified and my actual code is thousands of lines long. In the real program, the button is a context menu):
from spellchecker import SpellChecker
root = Tk()
notepad = Text(root)
notepad.pack()
spell_dict = SpellChecker()
def check_spelling(event):
global spell_dict
misspelt_words_list = []
paragraph_list = notepad.get('1.0', END).strip('\n').split()
notepad.tag_config('misspelt_word_tag', foreground='red', underline=1)
for word in paragraph_list:
if (word not in spell_dict) and (word not in misspelt_words_list):
misspelt_words_list.append(word)
elif (word in misspelt_words_list) and (word in spell_dict):
misspelt_words_list.remove(word)
notepad.tag_remove('misspelt_word_tag', 1.0, END)
for misspelt_word in misspelt_words_list:
misspelt_word_offset = '+%dc' % len(misspelt_word)
pos_start = notepad.search(misspelt_word, '1.0', END)
while pos_start:
pos_end = pos_start + misspelt_word_offset
notepad.tag_add("misspelt_word_tag",pos_start,pos_end)
pos_start = notepad.search(misspelt_word,pos_end,END)
button = Button(root, text = "This is a test", command = check_spelling)
button.pack()
root.mainloop()
Like I said before, if the user writes ll ll hello
, where 'll' is miss spelt (let's say the program will correct it to I'll), when the user presses the button it should replace all words written 'll', but not replace the 'll' in 'hello'.
THIS:
ll ll hello
-> I'll I'll hello
,
NOT:
ll ll hello
-> I'll I'll heI'llo
Thanks for your help.
(I'm using Windows 10 with Python 3.7)