我正在用python编写一个简单的人工神经网络。我需要能够将给定网络的所有数据保存到一个文本文件中。具体来说,我需要保存具有以下属性的节点列表:
名称、层号、增量值、连接权重
现在,我已经创建了自己的数据格式。看起来像这样:nodeName:layer,delta,connectionWeights;
例如
^{pr2}$
从一个对象创建这个数据并解析它以从数据创建一个对象实际上是相当容易的。但是,代码很难看,而且与我创建的格式非常特定。对于上下文,下面是我编写的用于解析的代码:def readInput(self, datafile):
f = open(datafile, 'r')
DNAstring = f.read()
f.close()
#first, parse each node
allNodes = DNAstring.split(";")
for nodey in allNodes:
n = nodey.partition(":") #partition separates node name from its data
name = n[0]
data = n[2].split(",") #each data element is separated by a comma
layer = data[0]
delta = data[1]
connections = {}
connectionList = data[2].split("#") #each connection is delimited by '#'
for c in connectionList:
x = c.partition("-")
name = x[0]
weight = x[2]
connections.update({name:weight})
print("updating connection with ", name, weight)
#now we have all the data for a node, create a node object
n = Node(name, layer, delta, connections)
self.nodes.update({name:n})
我的问题是:有没有更简单的方法来完成这个过程?在我看来,必须有一个比每次要将对象保存到文本文件时创建新的数据格式和解析函数更简单的解决方案。
我是否应该尝试使用XML或JSON之类的现有格式来使代码更易于理解/修改?我该如何用python来实现这一点呢?在
谢谢