1

I would like to troubleshoot an incorrect user input. It's exactly about finding the closest match from the "database".

database = ["dog", "cat", "bird"]
user_input = ["dog", "ccat", "ddogg", "horse", "fish"]
for i in user_input:
   match = difflib.get_close_matches('i', words)
match

But I get an empty list. Is there any simple solution to this problem? I haven't found anywhere how to get the result to the list using difflib.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • review: not being a python expert here. code seems quite incomplete. what is "words"? where does database come in? arent youcomparing "i" instead of user_input[i] ? – H.Hasenack Feb 02 '21 at 20:49

1 Answers1

4

Simpler way to achieve this is using list comprehension:

import difflib
database = ["dog", "cat", "bird"]
user_input = ["dog", "ccat", "ddogg", "horse", "fish"]

new_list = [difflib.get_close_matches(word, database) for word in user_input]

where new_list holds the closest match of word from user_input based on values from database as:

[['dog'], ['cat'], ['dog'], [], []]

Issue with your code is that you are passing i as string 'i' to get_close_matches function. Pass it as variable, and then append the match word to the list. For example, here's the working version of the code:

new_list = []
for i in user_input:
    match = difflib.get_close_matches(i, database)
                                  #   ^ don't pass this as string
    new_list.append(match)

# new_list: [['dog'], ['cat'], ['dog'], [], []]
   
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126