Suppose I want to check if a string has 'pizza' in it. But my user accidentally typed 'I want piztza' by accident (a simple typo). Is there a way to check if the user input approximately contains 'pizza'? Perhaps if only off by one letter.
4 Answers
Try using fuzzywuzzy from PyPI: https://pypi.org/project/fuzzywuzzy/. I am not very experienced with it, but the website should help.
3 Comments
fuzz.partial_ratio. See my comments under the question for an example.fuzzywuzzy would be one way to do this. fuzzywuzzy library compares the similarity between two strings. The Jaccard distance is one method that fuzzywuzzy uses. The Jaccard distance - measure any two sets.
This is what the formula looks like :
Here is a visual representation of the formula:
Here is how you could implement it:
from fuzzywuzzy import fuzz
similarity = fuzz.ratio("hello","world") # 0%
This will give you a ratio of how similar the words are. Here is another example:
from fuzzywuzzy import fuzz
similarity = fuzz.ratio("Austria","Australia") # Will give you 88%
Comments
you can use fuzzywuzzy package
from fuzzywuzzy import fuzz
q1 = input("type 'pizza': ")
compare = fuzz.ratio(q1, 'pizza')
if compare > 90:
print("you type pizza")
else:
print("you didn't type 'pizza'")
check his documentation for more uses, this is only a simple code.
1 Comment
Try this:
Sentence = "I want piztza"
Word = "pizza"
Same = False
for Sen_Word in Sentence.lower().split(" "):
if Sen_Word == Word:
Same = True
elif len(Sen_Word) == len(Word)+1:
Left_Count=0
Right_Count=0
for i, x in zip(Sen_Word, Word):
if i == x:
Left_Count += 1
else:
break
Letters_Left = min(len(Sen_Word), len(Word))-Left_Count
for i, x in zip(Sen_Word[::-1], Word[::-1]):
if Letters_Left - Right_Count > 0 and i == x:
Right_Count += 1
else:
break
if Left_Count + Right_Count == len(Word):
Same = True
print(Same)
or a shorter code:
Sentence = "I like piztza"
Word = "pizza"
Same = False
for Sen_Word in Sentence.split(" "):
if Sen_Word == Word: Same = True
elif len(Sen_Word) == len(Word)+1:
Left_Count=Right_Count=0
for i, x in zip(Sen_Word, Word):
if i == x: Left_Count += 1
else: break
Letters_Left = min(len(Sen_Word), len(Word))-Left_Count
for i, x in zip(Sen_Word[::-1], Word[::-1]):
if Letters_Left - Right_Count > 0 and i == x: Right_Count += 1
else: break
if Left_Count + Right_Count == len(Word): Same = True
print(Same)


fuzzywuzzypackage.from fuzzywuzzy import fuzzthenfuzz.partial_ratio("I want piztza", "pizza")gives 80, whereasfuzz.partial_ratio("I want fish", "pizza")gives 22. You would need to decide on an appropriate cutoff value.