我正在使用一些大型树,我希望能够将它们存储在文本文件中并在其他地方重建它们,而无需每次都重新创建树。
我正在使用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.
我怎么能把字典格式化为一个字符串放在一个文本文件中,我可以随后阅读以重建树?