Search code examples
pythonstartswith

Fuzzy Startswith


Is there a way to perform a fuzzy "startswith" such that if the first string starts with something close to the second, it will return true? My first thought is to use an edit distance threshold, but I'm not sure how to do that in the context of startswith.

Example:

first_str = "My nam is Hello World"
second_str = "My name is"        
first_str.startswith(second_str) == True

Solution

  • fuzzywuzzy can help sort of

    >>> from fuzzywuzzy import fuzz
    >>> fuzz.partial_ratio("my name is joran","my nam is")
    

    you will need to pip install fuzzywuzzy then you just need to pick a ratio that is "True" this does not necesarily mean "it startswith" we could do that with a helper function though

    def fuzzy_startswith(needle,haystack):
        n_words = len(needle.split())
        haystack_startswith = " ".join(haystack.split()[:n_words])
        return fuzz.ratio(needle,haystack_startswith)
    
    fuzzy_startswith("my nam is","my name is joran")