I see a number of issues with the loop code at the bottom of your outer function.
To start with, you're looping over q
, which I think is supposed to be a string containing any number of words. If you iterate directly on a string like this, you'll get individual characters, which I don't think you want. You probably should be using q.split()
or something similar to break up the string into a list of word strings.
The next issue is that you're calling word.lower()
(and later correct.lower()
) but not doing anything with the return value. Strings in Python are immutable, so methods like lower
return a new string with the requested changes, rather than modifying the existing string in place. You probably want word = word.lower()
(and correct = correct.lower()
). But this may have issues, as the changed capitalization may make the replace
call later not work properly. A better approach may be to treat case as significant and just remove the lower
calls.
A third issue is that your second loop is on q
again, rather than being on r
, which I think is supposed to be the list of correctly spelled words. (Note, you should also improve your variable names, so their meanings are obvious.) You probably want: for correct in r:
The final two (intertwined) issues are, I think, the ones you're actually asking about in the question. The first problem with your replace
call in the last line is that you're only passing one argument. str.replace
expects two (in addition to the instance it's being called on), so that won't work. Use replace(word, correct)
to replace each occurrence of the substring word
with correct
(though more on why this might not be the right thing to do later).
The other issue is the variable x
. You don't use x
anywhere else in the code, so I don't know what you intend it to be used for. If you're just trying to make a new string with the replacements in it, I'd suggest overwriting the q
variable with the return value of the replace
call:
q = q.replace(word, correct)
Then just add return q
at the bottom of the function.
Note, your function will still do the wrong thing in many cases, but fixing them will require a larger redesign. For one example of an error, if you have a string like "an"
as q
, and your dictionary contains ["and", "an"]
(with the longer word before the smaller one), your code will assume the an
word string is a misspelled version of and
and replace it. You probably need to check first if the word is correctly spelled (perhaps with word in r
) before checking if it's one character off any other words.
Another situation it will get wrong is when a misspelled word appears as a prefix in another word (which may or may not be spelled wrong itself). Try fixing "foo foobar"
with a word list of ["food"]
and you'll get "food foodbar"
, since the replace("foo", "food")
call had no respect for word boundaries.