In: Computer Science
In this exercise, you will build a basic spell checker.
Write a module called spell_checker.py. Your module should contain the following functions:
You may use "blurb.txt" to test out your module.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.
#important notes
for the below code to work properly, you must ensure following things:
1) aspell.txt file must be present on the same directory
2) aspell.txt file must be valid (exactly in the format specified)
3) blurb.txt file must be present on the same directory
4) there should not be any punctuations in blurb.txt
failure to add aspell.txt and blurb.txt files will result in FileNotFoundException and that is not a mistake from my side..
#code
#spell_checker.py
def word_correct(word):
# opening aspell.txt file, make sure file exist on the same directory
file = open('aspell.txt', 'r')
# looping through each line in file
for line in file:
# removing trailing newline and splitting line into words (by white space)
words = line.strip().split(" ")
# if word is in resultant list, closing file, returning first word on the list
if word in words:
file.close()
return words[0]
# if not found, closing file and returning word unchanged
file.close()
return word
def line_correct(line):
corrected = ''
# looping through each word in line
for word in line.split():
# appending corrected word to corrected string followed byt a space
corrected += word_correct(word) + " "
# returning corrected after removing stray " " at the end
return corrected.rstrip(' ')
def file_correct(filename):
# creating output file name. for example, if input file name is "data.txt", output file name
# will be "data_corrected.txt"
outputfilename = filename[0:filename.rfind('.')] + "_corrected" + filename[filename.rfind('.'):]
# opening input file and output file
inf = open(filename, 'r')
outf = open(outputfilename, 'w')
# looping through each line
for line in inf:
# correcting current line, writing to outf
outf.write(line_correct(line.strip()) + "\n")
# closing both file, saving changes
inf.close()
outf.close()
# code for testing with "blurb.txt" file
# if everything works correctly, "blurb_corrected.txt" file will be generated.
if __name__ == '__main__':
file = 'blurb.txt'
file_correct(file)