answer-grading-app / HTR /spell_and_gramer_check.py
yamanavijayavardhan's picture
update_new_new
26f855a
raw
history blame
1.19 kB
from spellchecker import SpellChecker
import os
# Initialize spell checker globally
spell = None
def initialize_spell_checker():
global spell
if spell is None:
try:
spell = SpellChecker()
except Exception as e:
print(f"Error initializing spell checker: {str(e)}")
raise
def spell_grammer(text):
try:
# Initialize spell checker if not already done
initialize_spell_checker()
if not text or not isinstance(text, str):
return ""
# Split text into words
words = text.split()
# Find misspelled words
misspelled = spell.unknown(words)
# Correct misspelled words
corrected_words = []
for word in words:
if word in misspelled:
corrected_words.append(spell.correction(word))
else:
corrected_words.append(word)
# Join words back into text
corrected_text = ' '.join(corrected_words)
return corrected_text.strip()
except Exception as e:
print(f"Error in spell_grammer: {str(e)}")
return text