import re from spellchecker import SpellChecker # Pre-compile the regular expression PERCENTAGE_PATTERN = re.compile(r'^\d+%?$') def is_percentage_or_number(s): # re.match returns None if the string does not match the pattern return PERCENTAGE_PATTERN.match(s) is not None def correct_spelling(text): words = text.split() corrected_words = [] for word in words: if is_percentage_or_number(word): corrected_words.append(word) else: spell = SpellChecker() corrected_word = spell.correction(text) corrected_words.append(str(corrected_word)) # convert corrected word back to string corrected_text = ' '.join(corrected_words) return corrected_text