今年秋天,我用 Python 为编程类(class)做了一个项目,其中有一个 20 个问题的游戏,可以从用户的回答中学习。它使用基于对问题是/否回答的树,并为每个决定挑选独特的问题以及动物,以便在到达“分支”的末端时询问。
在类(class)快要结束时,我们用 C++ 做了一些工作(但我对它还很陌生),我想在休息期间制作该项目的 C++ 版本 - 这会让它变得更重要例如,作为可执行文件更容易运行。然而,我发现 C++ 对于 pickle 式数据存储没有太多选择,而且我认为 Boost.serialization 或 Boost.Python 不太适合这种情况。
是否有其他替代方案,或者您对如何在 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'))
如果我将数据保存到文件或数组中,我想不出一种方法来使树工作(而且我不是特别想创建一个动态数组,尽管我可以弄清楚如果存储东西在一个数组中最终工作。)这些问题是我不确定如何引用特定节点。还有其他选择,或者关于如何使用这些选项的想法吗?谢谢! (圣诞快乐!)
最佳答案
实际上 boost::serialization 效果很好,学习基础知识并不难。
但是,您可能会考虑一些稍高级别的库,例如 Protocol Buffer 。这样您就可以拥有适用于您的 python 和 C++ 版本的数据库。
编辑:boost::python 不是正确的解决方案,因为它只允许进行绑定(bind)。用它来保存数据真的很痛苦。
Boost Serialize 允许序列化(然后轻松保存在磁盘上)C++ 结构。只需尝试文档中的示例即可。
Protocol Buffer 是一种序列化格式,允许以二进制格式交换数据。格式定义良好,因此您可以用不同的语言读取/写入并交换数据。 在代码内部进行操作更容易,例如 XML:http://code.google.com/p/protobuf/ 不过,我认为这比 boost::serialize 需要更多的努力。无论如何,两者都值得学习,并且对进一步的项目很有用。
关于C++ 数据存储替代 Python pickle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14015252/