在python中将对象保存到文本文件的最佳方法?

时间:2014-02-20 16:27:23

标签: python parsing serialization encoding

我在python中编写一个简单的人工神经网络。我需要能够将给定网络的所有数据保存到文本文件中。具体来说,我需要保存具有以下属性的节点列表: 名称,图层编号,增量值,连接权重

现在,我已经创建了自己的数据格式。它看起来像这样:

nodeName:layer,delta,connectionWeights;

e.g。

a:1,.5,b-.5#c-.7;b:1,.75,c-.3#d-.4;c:2,.3,a-12#b-.4

从对象创建此数据并解析它以从数据创建对象实际上相当容易。但是,代码很难看,并且非常特定于我创建的格式。对于上下文,这是我编写的解析代码:

   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中执行此操作?

由于

0 个答案:

没有答案