Reputation: 11
I need a bit of help with this assignment (first time posting on SE so please excuse my lack of posting etiquette if any)
So for this code I had to write a spell checker. Basically what it is supposed to do is:
1.) Check through two lists (One is a dictionary, where we get all the correctly spelled words, the other is the user input list which should have an incorrectly spelled word or two)
2.) suggest a correct word in place of the misspelled word (example would be if I spelled heloo, the spell checker would say i spelled that wrong and would suggest the word is hello, help, etc.)
My biggest problem right now is at line 19, I am getting the list indices must be integers problem.
Any help is appreciated, and help with finishing this would also be much appreciated! I feel like outside of the syntax more could be improved upon. Thanks.
here is the code, it is not completely finished
import re
def words_from_file(filename):
try:
f = open(filename, "r")
words = re.split(r"[,.;:?\s]+", f.read())
f.close()
return [word for word in words if word]
except IOError:
print("Error opening %s for reading. Quitting" % (filename))
exit()
user_word = words_from_file('user_word.txt')
suggestion = words_from_file('big_word_list.txt')
sug_list = []
for a in user_word:
if user_word[a] not in suggestion:
print ("Spelling error: %s"%(user_word[a]))
for i in suggestion:
for j in suggestion[i]:
if len(suggestion[i][j]) == len(user_word[a]-2):
count = 0
similarities = len(user_word[a])
for k in suggestion[i][j]:
if suggestion[i][j][k] in suggestion:
count+=1
if count >= similarities:
sug_list.append(suggestion[i][j])
Upvotes: 1
Views: 84
Reputation: 20349
List can slice using integers
not str
Change
if user_word[a] not in suggestion: #to==> if a not in suggestion:
for j in suggestion[i]: #to==> for j in i
for k in suggestion[i][j]: #to==> for k in j
Also many errors slice errors
like suggestion[i][j][k]
etc
So generally
for i in [1,2,3]:
print(i) # gives 1,2,3.No need of [1,2,3][i]
Also, you can use range(len)
for a in range(len(user_word)):
if user_word[a] not in suggestion:
Upvotes: 1
Reputation: 5289
Change:
for a in user_word:
if user_word[a] not in suggestion:
Into:
for a in user_word:
if a not in suggestion:
because all items in user_word
list will be iterated using the a
variable. The a
will in each iteration contain a nonempty string obtained from the line split. You can only use numerical index with a list type. Originally you've used a string in place of numeric index which causes the error message.
Upvotes: 1