在Python2.7中用嵌套类实例保存dict

2024-09-29 19:28:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我尽量让这个简单点。基本上,我希望数据保存到一个文件中,然后检索它以便查询器.py工作,可以“记住”你的机器上教过的所有东西。原始代码可在http://www.strout.net/info/coding/python/questor.py网站上找到 如果我正确地阅读了代码,那么您将得到一个类似{key:{key:{key:class instance},class instance},class instance}的对象。(粗略估计)

请忽略unshed方法Save,我正在研究如何在不丢失任何嵌入实例的情况下pickle字典。在

下面是我试图通过pickler保存dict的尝试。有些代码尚未完成,但您应该能够了解我在尝试做什么。到目前为止,我所能做的就是检索最后一个问题/答案集。要么我的pickle没有保存嵌入的实例,要么当我保存pickle时它们实际上不在那里。我已经尽可能地遵循了意大利面条的路线,但似乎不知道如何设置一种方法来保存到文件而不丢失任何内容。 同样,我的文件也不一定是.txt,最初我将使用.data作为pickle。在

# questor.py 

# define some constants for future use
kQuestion = 'question'
kGuess = 'guess'
questfile = 'questfile.txt'

## Added
import cPickle as p
# create a file for questor
def questor_file():
    try:
        questor = open(questfile,'rb')
        try:
            q = p.Unpickler(questor)
            quest = q.load()
            questor.close()
            return quest
        except:
            print 'P.load failed'
    except:
        print 'File did not open'
        questor = open('questfile.data', 'wb')
        questor.close()
    return Qnode('python')

# 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

    ##Added
    ## Not sure where I found this, but was going to attempt to use this as a retreival method
    ## haven't gotten this to work yet
    def Load(self):
        f = open(self.questfile,'rb')
        tmp_dict = cPickle.load(f)
        f.close()    
        self.__dict__.update(tmp_dict) 

    ##Added
    # was going to use this as a save method, and call it each time I added a new question/answer
    def Save(self,node):
        f = open(self.questfile,'wb')
        quest = p.pickler(f)


    # 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}
        self.save(self.nodes)


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
    # This was supposed to assign the data from the file
    topNode = questor_file()


    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
        print
        done = not yesno("Do another? ")
    # Added
    # give me the dictionary    
    return result

# immediate-mode commands, for drag-and-drop or execfile() execution
if __name__ == '__main__':
    print "Let's play a game."
    print 'Think of something, just one thing.'
    print 'It can be anything, and I will try to guess what it is.'
    raw_input('Press Enter when ready.')
    print
    questdata = run()
    print
    # Added
    # Save the dictionary
    questor = open(questfile,'wb')
    q = p.Pickler(questor)
    q.dump(questdata)
    questor.close()
    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)"

# end of questor.py

Tags: andthetoselfnodeforreturnif
1条回答
网友
1楼 · 发布于 2024-09-29 19:28:31

想到的一种方法是创建所有节点的列表并保存它。。。他们应该自己保留内部指针。在

在文件顶部声明一个节点列表(并使用pickle。。。只是因为我更熟悉)

import pickle
kQuestion = 'question'
kGuess = 'guess'
questfile = 'questfile.txt'
nodes = []
....

将加载方法更改为类似

^{pr2}$

更改类构造函数,使其将每个节点添加到节点

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

在它的末尾,如果添加了save dictionary,请保存节点列表

questor = open(questfile,'wb')
q = pickle.dump(nodes,questor)

确保在提示时键入no退出程序。。。在

你也可以把它保存到一个数据库或其他什么,但你仍然需要存储每个节点,这可能会更复杂。。。我认为这个方法应该很好,(虽然可能有更自然的方法来保存树结构)。。。在

相关问题 更多 >

    热门问题