用C++数据存储代替Python PI

2024-06-29 01:10:22 发布

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

今年秋天,我在Python中为一个编程类做了一个项目,其中有一个20个问题风格的游戏,可以从用户的反应中学习。它使用一棵基于是/否回答问题的树,并在每一个决定中提取出独特的问题,以及动物们在到达“树枝”末端时要问的问题。在

到课结束时,我们在C++中做了一些工作(但是我在这方面还是很新的),我希望在我的休息时间里做一个C++版本的项目,这将使它更容易运行,例如,一个可执行文件。不过,我发现C++没有很多选择泡菜风格的数据存储,我不认为。Boost.serialization系列化或者Boost.Python在这种情况下尤其有效。在

<> P>还有其他的选择,或者你有什么建议如何用C++的另一种方式来处理数据?在

原始的Python代码包括:

    def check(self):
        correct, lastnode = self.ask(self.root) #lastnode is the closest guess to the new animal
        if correct =='n':
            print("Rats! I didn't get it. Please help me improve.")
            newanimal = AnTreeNode(input("What is your animal? "))
            oldanimal = lastnode
            newquestion = input("Please enter a yes/no question that would\n select between a(n) %s \
and a(n) %s: " %(newanimal,lastnode.data))+" "
            direction = input("What would be the correct answer for a(n) %s? " %newanimal)
            newnode = AnTreeNode(newquestion, parent = lastnode.parent)
            if lastnode.parent == None:
                self.root = newnode
            elif lastnode.parent.yes == lastnode:
                newnode.parent.yes = newnode
            else:
                newnode.parent.no = newnode
            if direction == 'y':
                newnode.yes, newnode.no = newanimal, oldanimal
            elif direction == 'n':
                newnode.yes, newnode.no = oldanimal, newanimal
            newanimal.parent = newnode
            oldanimal.parent = newnode
            self.dumpTree()
        elif correct == 'y':
            print("I am soooo smart!")

    def loadTree(self):
        try:
            f = open(self.treefile, "rb")
            self.root = pickle.load(f)
        except:
            self.root = AnTreeNode("frog")  

    def dumpTree(self):
        pickle.dump(self.root, open(self.treefile, 'wb'))

如果我把数据保存到文件或数组中,我想不出一种方法来让树工作(我也不想创建一个动态数组,尽管我可以弄清楚在数组中存储的内容是否有效)的问题是,我不确定如何引用特定的节点。还有什么其他的选择,或者关于如何处理这些问题的想法?谢谢!(圣诞快乐!)在


Tags: the数据noselfifdefrootyes
2条回答

http://www.picklingtools.com中有一个开源C++库 这允许您在C++中处理对象(可能允许您重用)。 pickled文件)。最好是序列化标准 Python数据结构(dict、list、tuples、int、float等),但是可以工作 对于需要一些工作的类(毕竟,Python类通常使用 名称空间的dict)。在

一个简单的例子展示了如何使用picklingtools库(并使其正常工作 用C++和Python)

#include "chooseser.h"
#include <iostream>

int main (int argc, char **argv)
{
   // Create a Python style dictionary
   Val v = Tab("{'a':1, 'b':2.2, 'c':'three', 'nested':{ 'zz':1 }");
   v["d"] = "something";

   // print out a nested key
   cout << v["nested"]["zz"] << endl;  

   // Pickle the data structure to disk
   DumpValToFile(v, "state.p0", SERIALIZE_P2);

//  # Python side would read this same file with
// >>> import cPickle
// >>> result = cPickle.load( file('state.p0') ) # load fiigures out which prototcol

}

我可能会用字典或列表来建立你的树:

^{pr2}$

这样,你可以在C++和Python之间来回翻阅字典或者做列表,然后做你需要的。一切尽你所能。在

关于如何在C++中进行酸洗和解菜的研究有重要的文献资料。 “文档”选项卡下的网站。最好开始的地方可能是 http://www.picklingtools.com/documentation与{a3}一起使用。在

警告!前方危险! 你可以用C++来序列化类(这样你在Python中的类就有一个C++等价物),但是它很重要;如果你能在里面,你就更难了。 标准的Python数据结构,您的生活可以轻松得多。为了做到这一点,你会 然后用它的构造函数登记C++类 有了这个系统。您必须有一个构建函数(请参见下面的简单示例):

// When registering things with the factory, they take in some tuple
// and return a Val: REDUCE tend to be more for built-in complicated
// types like Numeric, array and complex.  BUILD tends to more for
// user-defined types.
typedef void (*FactoryFunction)(const Val& name, 
                                const Val& input_tuple, 
                                Val& environment,  
                                Val& output_result);


// Example of how user-defined classes would probably serialize: the
// user-defined classes tend to be built with BUILD instead of REDUCE,
// which passes slightly different arguments to the tuple.  As an
// example, magine a simple Python class:
//
//   class Scott(object) :
//     def __init__(self, n) : self.data = int(n)
//
// A dumps(a,2) (where a= Scott(100)) looks like
// '\x80\x02c__main__\nScott\nq\x01)\x81q\x02}q\x03U\x04dataq\x04Kdsb.'/
//
// type_object: a tuple (string_name, args). i.e., ('__main__\nScott\n', ()) 
// input: a dictionary                       i.e., {'data', 100 }
inline void BuildScottFactoryFunction (const Val& type_object, 
                       const Val& input,
                       Val& /* environment */,
                       Val& output_result)
{
  cout << "SCOTT:type_object:" << type_object << endl;
  cout << "SCOTT:input:" << input << endl;

  string name = type_object(0);
  Tup&   args = type_object(1);
  cout << "name:" << name << " args:" << args << endl;

  if (name!="__main__\nScott\n") throw runtime_error("Not right name");
  Val& result = input("data");
  output_result = result;
}

然后你必须在你自己的PickleLoader中注册这个类。在

PickleLoader p(buffer, buffer_len);
p.registerFactory("__main__\nScott\n", BuildScottFactoryFunction);

你可以让它工作,这样你就可以拥有Python和C++类了。 感觉也一样,用泡菜来交流,但这比看起来难 (部分原因是因为C++没有实际的运行时自省概念(它只限于 RTTI),所以你倾向于用元组来描述整个C++类。 字典,手动列表。然后向pickle加载程序注册这些函数。 这是可以做到的,但鉴于你的问题很简单,我会坚持下去 存储Python数据结构(列表、dict、tuples、int、float、string、None) 用这些来代表你的20个问题树。在

实际上boost::serialization工作得很好,学习基础知识也没那么难。在

但是,您可以考虑一些更高级别的库,如协议缓冲区。这样,您就可以拥有既可以用于Python又可以用于C++版本的数据库。在

EDIT:boost::python不是正确的解决方案,因为它只允许进行绑定。用它来保存数据真的很痛苦。在

BooServices允许序列化(然后很容易地保存在磁盘上)C++结构。请尝试文档中的示例。在

协议缓冲区是一种串行化格式,允许以二进制格式交换数据。格式定义良好,因此您可以从不同的语言读/写并交换数据。 更容易在代码内部进行操作,例如XML:http://code.google.com/p/protobuf/ 但是,我认为它需要比boost::serialize更多一点的工作。任何方法,这两种方法都是值得学习的,并将有助于进一步的项目。在

相关问题 更多 >