从文本文件(Python)中的任何树创建一个巨大的树



我正在使用一些巨大的树,我希望能够将它们存储在文本文件中并在其他地方重建它们,而不必每次都重新创建树。

我正在使用AnyTree来制作我的树。这些树包含 numpy 数组,因此不支持 JSON 转换。我将它们导出为嵌套词典。

这就是我将树写入文本文件的方式。

#Exports the tree to the given filename as a dictionary
def TreetoDict(filename, root):
exporter = DictExporter()
dictoutput = exporter.export(root)
string = str(dictoutput)
with open(filename,"w") as f:
f.write(string)
f.close()
print("Finished writing")
return dictoutput

由于树太大了,我认为在未经我同意的情况下,将字典变成字符串会以" "的形式放置很多换行符。

这是文本文件的外观。

("{'center': array([0, 0, 0]), 'radius': 2, 'name': '([0 0 0],2)', "
"'numpoints': 0, 'centerofmass': array([0, 0, 0]), 'children': [{'center': "
"array([1., 1., 1.]), 'radius': 1.0, 'name': '([1. 1. 1.],1.0)', 'numpoints': "
"0, 'centerofmass': array([0, 0, 0]), 'children': [{'center': array([1.5, "
"1.5, 1.5]), 'radius': 0.5, 'name': '([1.5 1.5 1.5],0.5)', 'numpoints': 0, "
"'centerofmass': array([0, 0, 0])}, {'center': array([1.5, 1.5, 0.5]), "
"'radius': 0.5, 'name': '([1.5 1.5 0.5],0.5)', 'numpoints': 0, "
"'centerofmass': array([0, 0, 0]), 'children': [{'center': array([1.75, 1.75, "
"0.75]), 'radius': 0.25, 'name': '([1.75 1.75 0.75],0.25)', 'numpoints': 0, "
"'centerofmass': array([0, 0, 0]), 'children': [{'center': array([1.875, "
"1.875, 0.875]), 'radius': 0.125, 'name': '([1.875 1.875 0.875],0.125)', "
"'numpoints': 0, 'centerofmass': array([0, 0, 0])}, {'center': array([1.875, " etc.

如何将字典格式化为字符串以放入文本文件中,随后可以读取该文件以重建树?

这似乎是XML的合适用例

https://www.w3schools.com/xml/xml_tree.asp

有许多库支持: https://docs.python.org/2/library/xml.etree.elementtree.html

相关内容

最新更新