Python将选项卡式文本文件读入一系列列表

时间:2010-11-11 18:43:58

标签: python

嗨,作为一个不熟悉的python用户,我将非常感谢以下任何帮助 编程挑战: 我有一个带有列表数据的文本文件,我想读它并放置值 在每一行上进入不同的python列表。 该文件如下所示:

 1  303233.479  233942.326     52.500       0.000  97 47 39.5    INFINITY     0.00034     0.00000 PBT  PBT  A001 B001  
 2  303386.031  233921.445     52.553     153.975  97 47 39.5    INFINITY     0.00034     0.00000 TS        A001
 3  303397.931  233919.897     52.557     165.975  96 38 54.2     -300.000    0.00034     0.00000 SC        A002
 4  303405.224  233919.137     52.559     173.308  95 14 52.6     -300.000    0.00034     6.25000      PC        B002

有13个列,我想将这些值放入13个列表中,我知道如何做到这一点 对于几个colums但是我对13个colummns如何做这个有点感到难过。

#Here is my pathetic attempt at this

pntnums = [] #a
xcogo = [] #b
ycogo = [] #c
zcogo = [] #d
chain = [] #e
bearing = [] #f
rad = [] #g
grad = [] #h
mval = [] #i
HCOD = [] #j
VCOD = [] #k

fd = file("align.txt").readlines():
    a, b, c, d, e, f, g, h, i, j, k,  = [int(s) for s in l.split()]  
    pntnums.append(int(a))  
    xcogo.append(int(b))  
    ycogo.append(int(c)) 
    zcogo.append(int(d)) 
    chain.append(int(e)) 
    bearing.append(int(f)) 
    rad.append(int(g))  
    grad.append(int(h))  
    mval.append(int(i)) 
    HCOD.append(int(j)) 
    VCOD.append(int(k)) 
for val in pntnums:
    print val 

#and the corresponding output:
Traceback (most recent call last):
  File "C:\MYPY\test.py", line 2, in <module>
    dataDict = dict(zip([float(i[1]) for i in data], [j[0] for j in data]))
IndexError: list index out of range

任何有关这方面的帮助都会非常受欢迎(evan a url),因为我搜索过并找不到解决方案。

newuser

1 个答案:

答案 0 :(得分:4)

你应该使用csv.reader;这是一个Python内置类,专门用于读取这样的文件。

>>> import csv
>>> fieldnames = ("pntnums", "xcogo", "ycogo", "zcogo", "bearing",
                  "rad", "grad", "mval", "HCOD", "VCOD")
>>> reader = csv.DictReader(open(...), delimiter="\t", fieldnames=fieldnames)

然后你可以迭代reader的元素,它会给你字典:

>>> import pprint
>>> for row in reader:
...     pprint.pprint(row)
...
{None: ['0.00000', 'PBT PBT', 'A001 B001  '],
 'HCOD': 'INFINITY',
 'VCOD': '0.00034',
 'bearing': '0.000',
 'grad': '47',
 'mval': '39.5',
 'pntnums': '1',
 'rad': '97',
 'xcogo': '303233.479',
 'ycogo': '233942.326',
 'zcogo': '52.500'}
{None: ['0.00000', 'TS', 'A001'],
 'HCOD': 'INFINITY',
 'VCOD': '0.00034',
 'bearing': '153.975',
 'grad': '47',
 'mval': '39.5',
 'pntnums': '2',
 'rad': '97',
 'xcogo': '303386.031',
 'ycogo': '233921.445',
 'zcogo': '52.553'}
{None: ['0.00000', 'SC', 'A002'],
 'HCOD': '-300.000',
 'VCOD': '0.00034',
 'bearing': '165.975',
 'grad': '38',
 'mval': '54.2',
 'pntnums': '3',
 'rad': '96',
 'xcogo': '303397.931',
 'ycogo': '233919.897',
 'zcogo': '52.557'}
{None: ['6.25000', 'PC', 'B002'],
 'HCOD': '-300.000',
 'VCOD': '0.00034',
 'bearing': '173.308',
 'grad': '14',
 'mval': '52.6',
 'pntnums': '4',
 'rad': '95',
 'xcogo': '303405.224',
 'ycogo': '233919.137',
 'zcogo': '52.559'}

(数据可能与此处的字段不完全匹配,因为我没有原始的以制表符分隔的文本,只是我可以从SO中复制粘贴的内容。如果您将原始文本提供给它,它将会起作用file =)。)