[Tutor] addressbook program

FT chester_lab at fltg.net
Sat Jun 28 19:57:39 CEST 2008


 

Hi Danny,

    This is another version of that same sample. You will note that it also has a voice to it. Along with that keyboard commands are from the get input that is the Microsoft input prompt. I modified the raw_input command by by-passing it.

    I am using the built in Microsoft SAPI 5 engine if you have an XP or Vista machine. If no speech then download it. This will give you something else to play with while learning.

    Study this, for it uses lists to get the option and hitting enter. And uses a dictionary to make a command from a key hit using the extended keyboard commands.

    Now in the program you will also see if statements depending on the key you hit and at the moment it is just the options on the list, one letter, then hit enter, choose from the list by using the cursor keys and you can even adjust the voices by using the Ins...PgDn keys. Along with s,f, and m keys.

    This address book program does add a feature or 2 from the original example, play with it, study it, and do what you want with it. It is attached along with my speech module for probably the email will mess up the indents.

    Have fun.

        Bruce


#Loading the Address Book using a global file name:
import os, time
#KEYBOARD COMMANDS!
import msvcrt
#ALT CURSOR UP, CURSOR LEFT, CURSOR RIGHT, CURSOR DOWN, SOL, EOL, PGUP, AND PGDN
MKS0 = {chr(152): "NAVUD", chr(155): "NAVLD", chr(157): "NAVRD", chr(160): "NAVDD", chr(151): "CMAP", chr(163): "CPRB", chr(159): "CMRS", chr(161): "CLRS"} #ALT PAGE KEYS!
#CTRL CURSOR UP, CURSOR LEFT, CURSOR RIGHT, CURSOR DOWN, SOL, EOL, PGUP, AND PGDN
MKS224 = {chr(141): "NAVU4", chr(115): "NAVL4", chr(116): "NAVR4", chr(145): "NAVD4", "R":"R", "S":"S", "G": "G", "O": "O", "I": "I", "Q": "Q", "u": "u", "v": "CPHA", "w": "CMAP", chr(134): "CGAL", "H": "NAVU", "K": "NAVL", "M": "NAVR", "P": "NAVD"}
import Sapi5
tts = Sapi5.Create()
tts.Volume = 100
tts.Rate = 1
purge = tts._purge
async = tts._async
tts.Speak( 'This is the default voice!', async, purge)
tts.Speak( 'The number of voices is: %d' % tts.getVoiceCount())
ctrl4V = {"vl":100, "rl":1, "pl":0, "v":"Sam"}

#MAKE UP A NEW NAME FOR THE FIRST LOAD ADDRESS BOOK!
FILE_NAME = "add_book.txt"
OPTIONS = 7
def read_Book (book):
    if os.path.exists(FILE_NAME):
        store = open(FILE_NAME,'r')
        for line in store:
            name = line.rstrip()
            entry = store.next().rstrip()
            book[name] = entry
        store.close()

#Notice the use of rstrip() to remove the new-line character from the end of the line. 
#Also notice the next() operation to fetch the next line from the file within the loop. 

#Finally #notice that we defined the filename as a module level variable so we 
#can use it both in #loading and saving the data.

#Saving the Address Book
def save_Book (book):
    store = open(FILE_NAME, 'w')
    for name,entry in book.items():
        store.write(name + '\n')
        store.write(entry + '\n')
    store.close()
    print "%s File Saved and Closed!" % FILE_NAME

#Notice we need to add a newline character ('\n')
#when we write the data.

#Copying the Address Book With New Name!
def copy_Book (book):
    save = 1
    file_name2 = text_Input(" Enter Name Of File To Save Address Book:")
    if file_name2 == "":
        print "No File Saved!"
        save = 0
    if save == 1:
        try:
            store = open(file_name2, 'w')
        except:
            print "File Error! No File Saved!"
            save = 0
    if save == 1:
        for name,entry in book.items():
            store.write(name + '\n')
            store.write(entry + '\n')
        store.close()
        print "%s File Saved and Closed!" % file_name2

#Getting User Input
def get_Choice( menu, msg=""):
    e=1
    while e==1:
        e=0
        try:
            choice =  key_input(msg)
        except:
            choice=0
#        choice = choice.lower()
        if choice not in "123456sfmHKMPqGOIQRSXXX":
            e=1
            print "Bad Entry, %s not an option!" % choice
            msg = "Select a choice(1-%d, q): " % (len(menu)-1)
    return choice


#DO TEXT INPUT WITH ENTRY ON NEXT LINE!
def text_Input(prompt):
    print prompt
    return (raw_input(">> "))

#Adding an Entry
def add_Entry (book):
    name = text_Input("Enter a name: ")
    if name != "":
        entry = text_Input("Enter Street, City/Town and Phone Number: ")
    if name != "" and entry != "":
        book[ name.capitalize()] = entry
    else:
        print "No entry saved!"

#EDIT ENTRY!
def edit_Entry (book):
    name = text_Input("Enter a name: ")
    if name in book:
        print "%s > %s" % (name, book[name])
        entry = text_Input("Enter Street, City/Town and Phone Number: ")
    else:
        name = ""
    if name != "" and entry != "":
        book[name] = entry
    else:
        print "No edit!"

#Removing an entry
def remove_Entry (book, del_Book):
    name = text_Input("Enter a name: ")
    if name in book:
        print "%s Deleted!" % name
        del_Book[name] = book[name]
        del(book[name])
    else: print "Sorry, no entry for: ", name

#RESTORING A DELETED ENTRY!
def restore_Entry (book, del_book):
    if len( del_book) == 0:
        print "Nothing To Restore!"
    else:
        for name,entry in del_book.items(): pass
        print "%s At: %s" % (name, entry)
        book[name] = entry
        del(del_book[name])

#Finding an entry
def find_Entry (book):
    name = text_Input("Enter A Name: ")
    if name.capitalize() in book:
        print "%s > %s" % (name, book[name])
    else: print "Sorry, no entry for: ", name.capitalize()

def key_input( msg):
    "ENTER A KEY OR FUNCTION KEY, (ALT, CTRL, SHIFT...KEY)"
    # clear the keyboard buffer
    ch=""; ch1=""; sch=""
    while msvcrt.kbhit():
        ch = msvcrt.getch()
#    PlaySound ("Federation_Scan.ogg", 2, -1) #PLAY ANY SOUND HERE!
#    print "| "
#    print "Hit Return Or Escape To Quit or Move Using Cursor Keys:"
    if msg != "":
        print msg,
    while ch != chr(27) and ch != chr(13) and ch1 != chr(0) and ch1 != chr(224):
        ch1 = msvcrt.getch()
        ch = ch1
        if ch1 == chr(0) or ch1 == chr(224):
            ch = msvcrt.getch()
            sch = ch
            print
            if ch not in MKS0 and ch not in MKS224: print "ch=%d ch1=%d" % (ord(ch), ord(ch1))
        else:
#            ch = ch.upper()
            ch = ch.lower()
#            if ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
            if ch in "abcdefghijklmnopqrstuvwxyz":
                msvcrt.putch(ch)
                sch=ch
            elif ch == chr(8) and len(sch)>0:
                msvcrt.putch(ch)
                sch = sch[:len(sch)-1]
    if ch == chr(27): 
        i=len(sch)
        while i>0:
            i-=1
            msvcrt.putch(chr(8))
        sch="XXX"
        print sch
    print
    return (sch)

def voiceControl( ctrl):
    "CONTROLS FOR VOICES!"
    if ctrl == "I":
        ctrl4V[ "vl"] += 5
        if ctrl4V[ "vl"] > 100:
            ctrl4V[ "vl"] = 100
            tts.setVolume( ctrl4V[ "vl"])
            tts.Speak('Volume Maximum!', async, purge)
        else:
            tts.setVolume( ctrl4V[ "vl"])
            tts.Speak('Volume Up!', async, purge)
    elif ctrl == "Q":
        ctrl4V[ "vl"] -= 5
        if ctrl4V[ "vl"] <= 0:
            ctrl4V[ "vl"] = 0
            tts.setVolume( 100)
            tts.Speak('Volume Minimum!', async, purge)
            time.sleep(.2)
            tts.setVolume( ctrl4V[ "vl"])
        else:
            tts.setVolume( ctrl4V[ "vl"])
            tts.Speak('Volume Down!', async, purge)
    elif ctrl == "G":
        ctrl4V[ "rl"] += 1
        tts.setRate( ctrl4V[ "rl"])
        tts.Speak('Rate Up!', async, purge)
    elif ctrl == "O":
        ctrl4V[ "rl"] -= 1
        tts.setRate( ctrl4V[ "rl"])
        tts.Speak('Rate down!', async, purge)
#PITCH FUNCTION DOES NOT EXIST FOR THE MICROSOFT ENGINE NOR IN PYTTS BUT IN MINE AS AN XML COMMAND!
    elif ctrl == "R":
        ctrl4V[ "pl"] += 1
        tts.setPitch( ctrl4V[ "pl"])
        tts.Speak('Pitch Up!', async, purge)
    elif ctrl == "S":
        ctrl4V[ "pl"] -= 1
        tts.setPitch( ctrl4V[ "pl"])
        tts.Speak('Pitch down!', async, purge)
    elif ctrl == "f":
        tts.setVoiceByName('Mary')
        ctrl4V[ "v"] = 'Mary'
        tts.Speak('Mary!', async, purge)
    elif ctrl == "m":
        tts.setVoiceByName('Mike')
        ctrl4V[ "v"] = 'Mike'
        tts.Speak('Mike!', async, purge)
    elif ctrl == "s":
        tts.setVoiceByName('Sam')
        ctrl4V[ "v"] = 'Sam'
        tts.Speak('Sam!', async, purge)

#MAKE ALL EDIT SELECTIONS A VERBALIZED LIST!
def menuOptions(spk, limit=OPTIONS):
    "ENTER CHOICE FOR LEVEL NUMBER!"
    tts.Speak(" %s 1" % spk)
    choice=1
    msg=str(choice)
    while True:
        event = pygame.event.poll()
        if event.type == pygame.QUIT:
            sys.exit()
            break
        elif event.type == pygame.KEYDOWN:
            key = event.key
#            keymod = event.mod
            if key==K_ESCAPE:
                sys.exit()
                break

            if key == K_UP:
                if choice>1: choice-=1
                msg=str(choice)
                tts.Speak(" %s? " % msg, async, purge)
            elif key == K_DOWN:
                if choice<limit: choice+=1
                msg=str(choice)
                tts.Speak(" %s? " % msg, async, purge)
            elif key == K_RETURN:
                tts.Speak(" Answer Is, %s! " % msg, async, purge)
                return (choice)
            else:
                tts.Speak(" %s %s!" % (spk, msg), async, purge)

#Quitting the program
#Actually I won't write a separate function for this, instead 
#I'll make the quit option the test in my menu while loop. 
#So the main program will look like this:

def main():
    the_Menu = [
"1) Add Entry",
"2) Remove Entry",
"3) Restore Entry",
"4) Find Entry",
"5) Edit Entry",
"6) Copy Book",
"q) Quit and save",
"s) Sam Voice",
"f) Mary Voice",
"m) Mike Voice",
]   #END OF LIST!
# MAKE LIST FOR DATA AND FETCH DATA ON START-UP!
    the_Book = {}
    book_Dels = {}
    read_Book (the_Book)
# MAKE CHOICES UNTIL QUITTING!
    choice = "0"
    mc=0
    for i in range( len(the_Menu)): print the_Menu[i]
    while choice not in "qXXX":
        choice = get_Choice( the_Menu)
        if choice=="": choice = the_Menu[mc][0]
        if choice == "1":
            add_Entry (the_Book)
        elif choice == "2":
            remove_Entry (the_Book, book_Dels)
        elif choice == "3":
            restore_Entry (the_Book, book_Dels)
        elif choice == "4":
            find_Entry (the_Book)
        elif choice == "5":
            edit_Entry (the_Book)
        elif choice == "6":
            copy_Book (the_Book)
        elif choice in "GOIQRSsfm":
            voiceControl( choice)
        elif choice in "HK":
            if mc<1: mc=0
            else: mc-=1
            tts.Speak( the_Menu[mc], async, purge)
            print the_Menu[mc]
        elif choice in "MP":
            mc+=1
            if mc>=len( the_Menu): mc=len( the_Menu)-1
            tts.Speak( the_Menu[mc], async, purge)
            print the_Menu[mc]
        elif choice not in "q XXX":
            print "Invalid choice, try again"
    if choice == "q":
        save_Book (the_Book)
        e = raw_input(" Hit Enter Key To Quit! ")
    else:
        tts.Speak( "Escaping!")
        print "Escaping!"

#Now the only thing left to do is call the main() function when the program is run, 
#and to do that we use a bit of Python magic like this:

if __name__ == "__main__":
    main()

#This mysterious bit of code allows us to use any python file as a module by
#importing it, or as a program by running it. The difference 
#is that when the program is imported, 
#the internal variable __name__ is set to the module name but
# when the file is run, the value of __name__ is set to "__main__". 
#Sneaky, eh?
#Now if you type all that code into a new text file 
#and save it as addressbook.py,
#you should be able to run it from an OS prompt by typing:
#c:\python25\ python25 address.py
#If Your Path Has Been Set Just Type:
#Address
#NOTE:
#python25 is assumed to be loaded onto your machine.
#If you have told your computer to run .py using python25 path, then just click on the Address.py file from explorer

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080628/2e669997/attachment-0001.htm>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Address.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20080628/2e669997/attachment-0002.txt>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Sapi5.py
URL: <http://mail.python.org/pipermail/tutor/attachments/20080628/2e669997/attachment-0003.txt>


More information about the Tutor mailing list