Last active
August 5, 2023 06:37
-
-
Save 0x4f53/66a784c4c5921359299d603419a8f01b to your computer and use it in GitHub Desktop.
Check if a similar-looking word exists in a given string or paragraph.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def similar_word(string, substring): | |
threshold=2 | |
def levenshtein_distance(s1, s2): | |
m, n = len(s1), len(s2) | |
dp = [[0] * (n + 1) for _ in range(m + 1)] | |
for i in range(m + 1): | |
for j in range(n + 1): | |
if i == 0: dp[i][j] = j | |
elif j == 0: dp[i][j] = i | |
elif s1[i - 1] == s2[j - 1]: dp[i][j] = dp[i - 1][j - 1] | |
else: dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) | |
return dp[m][n] | |
for i in range(len(string) - len(substring) + 1): | |
distance = levenshtein_distance(string[i:i + len(substring)], substring) | |
if distance <= threshold: return True | |
return False | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A simple Python function that uses Levenshtein distancing and string splitting to check if a similar-looking word exists in a given string or paragraph.
String: The quick brown fox jumped over the lazy dogs
Search: doggies
Result:
True
Search: cat
Result:
False