#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2005
    Posts
    4
    Rep Power
    0

    Question Help with Questor.py code


    Hi I would like some help with the following code. I have tried everything but can't figure out how to make this simple program store the input of a user into a file and retrieve it the next time it is opened. I have it where it stores all the data in the file but only retrieves part of that file. Any advice would be great.


    #!/usr/bin/Python
    #Filename: questor.py

    # define some constants for future use

    import cPickle as p
    #import pickle as p
    questionsfile = 'questions.data'

    kQuestion = 'question'
    kGuess = 'guess'

    # define a function for asking yes/no questions
    def yesno(prompt):
    ans = raw_input(prompt)
    return (ans[0]=='y' or ans[0]=='Y')

    # define a node in the question tree (either question or guess)
    class Qnode:

    # initialization method
    def __init__(self,guess):
    self.nodetype = kGuess
    self.desc = guess

    # get the question to ask
    def query(self):
    if (self.nodetype == kQuestion):
    return self.desc + " "
    elif (self.nodetype == kGuess):
    return "Is it a " + self.desc + "? "
    else:
    return "Error: invalid node type!"

    # return new node, given a boolean response
    def nextnode(self,answer):
    return self.nodes[answer]

    # turn a guess node into a question node and add new item
    # give a question, the new item, and the answer for that item
    def makeQuest( self, question, newitem, newanswer ):

    # create new nodes for the new answer and old answer
    newAnsNode = Qnode(newitem)
    oldAnsNode = Qnode(self.desc)

    # turn this node into a question node
    self.nodetype = kQuestion
    self.desc = question

    # assign the yes and no nodes appropriately
    self.nodes = {newanswer:newAnsNode, not newanswerldAnsNode}



    def traverse(fromNode):
    # ask the question
    yes = yesno( fromNode.query() )

    # if this is a guess node, then did we get it right?
    if (fromNode.nodetype == kGuess):
    if (yes):
    print "I'm a genius!!!"
    return
    # if we didn't get it right, return the node
    return fromNode

    # if it's a question node, then ask another question
    return traverse( fromNode.nextnode(yes) )

    def run():
    # start with a single guess node
    # topNode = Qnode('python')
    # if len(questionsfile) != 0:
    f = file(questionsfile)
    if f.read(1) != "":
    f.seek(0)
    storedquestions = p.load(f)
    topNode = storedquestions
    else:
    topNode = Qnode('python')
    done = 0
    while not done:
    # ask questions till we get to the end
    result = traverse( topNode )

    # if result is a node, we need to add a question
    if (result):
    item = raw_input("OK, what were you thinking of? ")
    print "Enter a question that distinguishes a",
    print item, "from a", result.desc + ":"
    q = raw_input()
    ans = yesno("What is the answer for " + item + "? ")
    result.makeQuest( q, item, ans )
    print "Got it."

    # repeat until done
    f = file(questionsfile, 'a')
    questions = result
    p.dump(questions, f) # dump the object to a file
    f.close()
    print

    done = not yesno("Do another? ")
    # Write to the file

    print



    # immediate-mode commands, for drag-and-drop or execfile() execution
    if __name__ == '__main__':
    run()


    print
    raw_input("press Return>")
    else:
    print "Module questor imported."
    print "To run, type: questor.run()"
    print "To reload after changes to the source, type: reload(questor)"
  2. #2
  3. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    We would like to help but please read the stickies at the top of the forum - they explain how to post Python code.

    Have fun,

    grim
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2005
    Posts
    4
    Rep Power
    0
    Sorry here is my code: Thanks again for any help I can get.

    Code:
    #!/usr/bin/Python 
    #Filename: questor.py        
    
    # define some constants for future use 
    
    import cPickle as p 
    #import pickle as p 
    questionsfile = 'questions.data' 
    
    kQuestion = 'question' 
    kGuess = 'guess' 
    
    # define a function for asking yes/no questions 
    def yesno(prompt): 
        ans = raw_input(prompt) 
        return (ans[0]=='y' or ans[0]=='Y') 
    
    # define a node in the question tree (either question or guess) 
    class Qnode: 
        
        # initialization method 
        def __init__(self,guess): 
            self.nodetype = kGuess 
            self.desc = guess 
    
        # get the question to ask    
        def query(self): 
            if (self.nodetype == kQuestion): 
                return self.desc + " " 
            elif (self.nodetype == kGuess): 
                return "Is it a " + self.desc + "? " 
            else: 
                return "Error: invalid node type!" 
    
        # return new node, given a boolean response 
        def nextnode(self,answer): 
            return self.nodes[answer] 
    
        # turn a guess node into a question node and add new item 
        # give a question, the new item, and the answer for that item 
        def makeQuest( self, question, newitem, newanswer ): 
    
            # create new nodes for the new answer and old answer 
            newAnsNode = Qnode(newitem) 
            oldAnsNode = Qnode(self.desc) 
    
            # turn this node into a question node 
            self.nodetype = kQuestion 
            self.desc = question 
    
            # assign the yes and no nodes appropriately 
            self.nodes = {newanswer:newAnsNode, not newanswer:oldAnsNode} 
        
        
    
    def traverse(fromNode): 
        # ask the question 
        yes = yesno( fromNode.query() ) 
        
        # if this is a guess node, then did we get it right? 
        if (fromNode.nodetype == kGuess): 
            if (yes): 
                print "I'm a genius!!!" 
                return 
            # if we didn't get it right, return the node 
            return fromNode 
        
        # if it's a question node, then ask another question 
        return traverse( fromNode.nextnode(yes) ) 
    
    def run(): 
        # start with a single guess node 
        # topNode = Qnode('python') 
       # if len(questionsfile) != 0: 
        f = file(questionsfile) 
        if f.read(1) != "": 
            f.seek(0)  
            storedquestions = p.load(f) 
            topNode = storedquestions 
        else: 
            topNode = Qnode('python') 
        done = 0   
        while not done: 
            # ask questions till we get to the end 
            result = traverse( topNode ) 
            
            # if result is a node, we need to add a question 
            if (result): 
                item = raw_input("OK, what were you thinking of? ") 
                print "Enter a question that distinguishes a", 
                print item, "from a", result.desc + ":" 
                q = raw_input() 
                ans = yesno("What is the answer for " + item + "? ") 
                result.makeQuest( q, item, ans ) 
                print "Got it." 
            
            # repeat until done 
            f = file(questionsfile, 'a') 
            questions = result 
            p.dump(questions, f) # dump the object to a file 
            f.close() 
            print 
            
            done = not yesno("Do another? ") 
            # Write to the file 
           
            print 
    
    
    
    # immediate-mode commands, for drag-and-drop or execfile() execution 
    if __name__ == '__main__': 
        run() 
    
        
        print 
        raw_input("press Return>") 
    else: 
        print "Module questor imported." 
        print "To run, type: questor.run()" 
        print "To reload after changes to the source, type: reload(questor)"
  6. #4
  7. Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Dec 2004
    Location
    Meriden, Connecticut
    Posts
    1,797
    Rep Power
    154
    Code:
    for line in file('thefileyouareusing'):
        if line == 'whatyouarelookingfor':
            do whatever you want
    Use that format for retrieving data from any file you desire. Also, look into the find() function.

    Comments on this post

    • Grim Archon disagrees : For text files, not binary data.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2005
    Posts
    4
    Rep Power
    0

    Thanks for your reply but:


    I need it to basically retrive all the data entered by a user that way when you open the file again it doesn't start over from scratch each time. I got it pulling some of the file but not all of it. ??????
  10. #6
  11. Mini me.
    Devshed Novice (500 - 999 posts)

    Join Date
    Nov 2003
    Location
    Cambridge, UK
    Posts
    783
    Rep Power
    13
    You are using a pickle file so you can't assume any particular order in the data it holds and in particular since it is a linked list of objects.
    Code:
        if f.read(1) != "": 
            f.seek(0)  
            storedquestions = p.load(f) 
            topNode = storedquestions
    f is your pickle you should not try to manipulate it yourself, if you want to do error handling then you should consider exceptions:
    Code:
        try: 
            storedquestions = p.load(f) 
            topNode = storedquestions 
        except: 
            print "Failed to load question tree!"
            topNode = Qnode('python')
    if you try
    Code:
    print storedquestions
    after each node manipulation do you get your questions in the structure you want?

    grim

IMN logo majestic logo threadwatch logo seochat tools logo