How to efficiently interpret phrases in a Python AI?
To compare the strings you can use Fuzzy string matching. FuzzyWuzzy is a python package that does this using the Levenshtein distance, which calculates the difference between two strings by counting the number of single character edits (insert, delete, substitute) that have to be done to make them equal.



To install the package you can use pip for example:

pip install fuzzywuzzy


Then you can use it to check the similarity between two strings (100 is the highest score; higher score means more similar):

&gt;&gt;&gt; from fuzzywuzzy import fuzz
&gt;&gt;&gt; fuzz.ratio("How are you?", "How are you?")
100
&gt;&gt;&gt; fuzz.ratio("How are you?", "How are you doing?")
80


Or, which might be most interesting to you, find the most similar string from a list of strings:

from fuzzywuzzy import process
choices = ['HI', 'HELLO', 'HEY', 'GOOD MORNING','TELL ME A JOKE', 'JOKE', 'FUNNY','GIVE ME A TIP', 'TIP', 'LESSON','WHAT IS YOUR NAME', 'WHO ARE YOU', 'HOW ARE YOU?']


You can get a list of the phrases with the highest score (parameter limit, 2 in this example):

&gt;&gt;&gt; process.extract("hello there", choices, limit=2)
[('HELLO', 90), ('HEY', 60)]
&gt;&gt;&gt; process.extract("please make a joke", choices, limit=2)
[('JOKE', 90), ('TELL ME A JOKE', 69)]


Or just get the one with the highest score:

&gt;&gt;&gt; process.extractOne("whoe are you?", choices)
('WHO ARE YOU', 96)
&gt;&gt;&gt; process.extractOne("I want a lesson", choices)
('LESSON', 90)


Note:

There are cases where another phrase might give a relatively high score also:

&gt;&gt;&gt; fuzz.ratio("How are you?", "Who are you?")
83


But as long as you also have "Who are you" and "How are you" in the list, they will be detected correctly:

&gt;&gt;&gt; process.extract("Who are you?", choices, limit=2)
[('WHO ARE YOU', 100), ('HOW ARE YOU?', 91)]
&gt;&gt;&gt; process.extract("How are you?", choices, limit=2)
[('HOW ARE YOU?', 100), ('WHO ARE YOU', 91)]




Also see: FuzzyWuzzy: Fuzzy String Matching in Python