[Tutor] Thank You! & Something for you [difflib in Python 2.1]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 12 Oct 2001 18:52:30 -0700 (PDT)


On Fri, 12 Oct 2001, Craig Carman wrote:

> Choose from:
>  *  Figaro Design
>  *  Beaded Design
>  *  Snake Design
      ^^^^^

You've reached Python-tutor, which, despite its name, has very little to
do with "Python reticulatus".  The name "Python" here refers to the highly
regarded "Monty Python" comedy group.  I guess "Python" could also refer,
distantly, to the name of a really nice programming language.


We're a group of tutors who help each other learn how to program, and your
question has very little content.  Still, even in the midst of your
confusion, we can try to help.


>From the snippet above, we could interpret that you're trying to get a
user to choose from a list of specific choices, maybe something like this:

###
What flavor of ice cream do you like the most?
Choose from the following:
    *  green tea
    *  rocky road
    *  vanilla
    *  chocolate
> Humperdinck
I don't know about Humperdinck.  Please try again.
> banilla
I don't know about banilla.  Please try again.
> vanilla
###


Here's one possible implementation for this alternative-choosing function:

### 
def chooseAnAlternative(alternatives):
    while 1:
        choice = raw_input("> ")
        if choice in alternatives:
            return choice
        print "I don't know about %s.  Please try again." % choice
###


This works... but we notice that program is a little unfriendly: it
doesn't accept any misspellings.  Even if someone is one letter off, our
program just clamps hands over its years and sings "I'm not listening..."


But this can be fixed!  We can make this program more forgiving with the
extremely cool 'difflib' module that's new with Python 2.1:

    http://python.org/doc/current/lib/module-difflib.html

difflib will, given a list of choices, try to find the very best choice,
even if the user misspells a word:

###
import difflib
def chooseAnAlternative(alternatives):
    while 1:
        choice = raw_input("> ")
	best_match = difflib.get_close_matches(choice, alternatives, 1)
        if best_match:
            return best_match[0]
        print "I don't know about %s.  Please try again." % choice
###


Here's a small test of this improved chooseAnAlternative() function:

###
>>> flavours = ['green tea', 'rocky road', 'vanilla', 'chocolate']
>>> chooseAnAlternative(flavours)
> rookie
I don't know about rookie.  Please try again.
> banilla
'vanilla'
>>> chooseAnAlternative(['to bluff', 'true love'])
> tooblaithe
I don't know about tooblaithe.  Please try again.
> to blove
'true love'
###


difflib does a very good job at trying to make sense out of the
incomprehensible.