Skip to main content
 首页 » 编程设计

python之将文件内容读入数组

2025年05月04日22davidwang456

我对 Python 有点熟悉。我有一个文件,其中包含我需要以非常具体的方式阅读的信息。下面是一个例子...

1 
6 
0.714285714286 
0    0    1.00000000000 
0    1    0.61356352337 
... 
-1  -1    0.00000000000 
0    0    5.13787636499 
0    1    0.97147643932 
... 
-1  -1    0.00000000000 
0    0    5.13787636499 
0    1    0.97147643932 
... 
-1  -1    0.00000000000 
0 0 0 0   5.13787636499 
0 0 0 1   0.97147643932 
.... 

所以每个文件都会有这个结构(制表符分隔)。

  • 第一行必须作为变量读入,第二行和第三行也是如此。
  • 接下来我们有四个代码块,由 -1 -1 0.0000000000 分隔。每个代码块都是“n”行长。前两个数字表示该行中的第 3 个数字要插入到数组中的位置/位置。仅列出唯一位置(因此,位置 0 1 将与 1 0 相同,但不会显示该信息)。
  • 注意:第 4 个代码块有一个 4 索引号。

我需要什么

  • 前 3 行作为唯一变量读入
  • 每个数据 block 读入一个数组,使用前 2(或 4)列数字作为数组索引,第 3 列作为插入数组的值。
  • 仅显示唯一的数组元素。我还需要用正确的值填充镜像位置(0 1 值也应该出现在 1 0 中)。
  • 最后一个 block 需要插入到一个 4 维数组中。

请您参考如下方法:

我重写了代码。现在它几乎就是您所需要的。您只需要微调即可。

我决定保留旧答案 - 也许它也会有所帮助。 因为新的功能已经够丰富了,有时候可能看不懂。

def the_function(filename): 
    """ 
    returns tuple of list of independent values and list of sparsed arrays as dicts 
    e.g. ( [1,2,0.5], [{(0.0):1,(0,1):2},...] ) 
    on fail prints the reason and returns None: 
    e.g. 'failed on text.txt: invalid literal for int() with base 10: '0.0', line: 5' 
    """ 
 
    # open file and read content 
    try: 
        with open(filename, "r") as f: 
            data_txt = [line.split() for line in f] 
    # no such file 
    except IOError, e: 
        print 'fail on open ' + str(e) 
 
    # try to get the first 3 variables 
    try: 
        vars =[int(data_txt[0][0]), int(data_txt[1][0]), float(data_txt[2][0])] 
    except ValueError,e: 
        print 'failed on '+filename+': '+str(e)+', somewhere on lines 1-3' 
        return 
 
    # now get arrays 
    arrays =[dict()] 
    for lineidx, item in enumerate(data_txt[3:]): 
        try: 
            # for 2d array data 
            if len(item) == 3: 
                i, j = map(int, item[:2]) 
                val = float(item[-1]) 
                # check for 'block separator' 
                if (i,j,val) == (-1,-1,0.0): 
                    # make new array 
                    arrays.append(dict()) 
                else: 
                    # update last, existing 
                    arrays[-1][(i,j)] = val 
            # almost the same for 4d array data 
            if len(item) == 5: 
                i, j, k, m = map(int, item[:4]) 
                val = float(item[-1]) 
                arrays[-1][(i,j,k,m)] = val 
        # if value is unparsable like '0.00' for int or 'text' 
        except ValueError,e: 
            print 'failed on '+filename+': '+str(e)+', line: '+str(lineidx+3) 
            return 
    return vars, arrays