Search code examples
pythonpython-3.xsearchlogic

How can I add tolerance to an input search engine


I have this code to search text in a big text file:

y = input("Apellido/s:").upper()
    for line in fread:

        if y in line:
            print(line)

How can I implement a way that it searches for similar text/autocorrect if nothing is found. Not as extensive as google does it, but just search for text that has maybe 1 more letter or an accent in a word. I can't imagine the algorithm to do it by myself.

I now that i have to add an if but im asking for the logic


Solution

  • You can do it using find_near_matches from fuzzysearch

    from fuzzysearch import find_near_matches
    y = input("Apellido/s:").upper()
        for line in fread:
            if find_near_matches(y, line, max_l_dist=2):
                print(line)
    

    find_near_matches return a list of matches if some found, if not match found it returns an empty array which is evaluated to false.

    max_l_dist option says the total number of substitutions, insertions and deletions (a.k.a. the Levenshtein distance)