Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match strings with possible typos? [closed]

I have multiple pdf converted into a text files and I want to search for a certain phrase that might be in the files. My problem is that the conversion between pdf and text file is not perfect so sometimes there are errors that appear in the text (such as missing spaces between word; mix-up between i, l, 1's; etc.)

I was wondering if there is any common technique to give me a "soft" search, something that looks at the hamming distance between two terms for example.

if 'word' in sentence:

vs

if my_search('word',sentence, tolerance):
like image 366
kkawabat Avatar asked Oct 22 '25 13:10

kkawabat


2 Answers

you can use something like this:

from difflib import SequenceMatcher

text = """there are 
some 3rrors in my text
but I cannot find them"""

def fuzzy_search(search_key, text, strictness):
    lines = text.split("\n")
    for i, line in enumerate(lines):
        words = line.split()
        for word in words:
            similarity = SequenceMatcher(None, word, search_key)
            if similarity.ratio() > strictness:
                return " '{}' matches: '{}' in line {}".format(search_key, word, i+1)

print fuzzy_search('errors', text, 0.8)

which should output this:

'errors' matches: '3rrors' in line 2
like image 133
Rumpelstiltskin Koriat Avatar answered Oct 24 '25 03:10

Rumpelstiltskin Koriat


fuzzywuzzy looks like it might work for you: https://github.com/seatgeek/fuzzywuzzy

like image 27
uncleshelby Avatar answered Oct 24 '25 03:10

uncleshelby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!