Extract Text Table From File

Laszlo Nagy gandalf at shopzeus.com
Mon Aug 27 07:07:37 EDT 2012


> Hi,
>
> Thank you for the information.
> The exact way I want to extract the data is like as below.
>
> TRG, MP and DATE and TIME is common for that certain block of traffic.
> So I am using those and dumping it with the rest of the data into sql.
> Table will have all headers (TRG, MP, DATE, TIME, R, TRAFF, NBIDS, CCONG, NDV, ANBLO, MHTIME, NBANSW).
>
> So from this text, the first data will be 37, 17, 120824, 0000, AABBCCO, 6.4, 204, 0.0, 115, 1.0, 113.4, 144.
How many blocks do you have in a file? Do you want to create different 
data sets for those blocks? How do you identify those blocks? (E.g. are 
they all saved into the same database table the same way?)

Anyway here is something:

import re
# AABBCCO     6.4     204     0.0   115    1.0    113.4     144
pattern = re.compile(r"""([A-Z]{7})"""+7*r"""\s+([\d\.]+)""")

#
# This is how you iterate over a file and process its lines
#
fin = open("test.txt","r")
blocks = []
block = None
for line in fin:
     # This is one possible way to extract values.
     values = line.strip().split()
     if values==['R', 'TRAFF', 'NBIDS', 'CCONG', 'NDV', 'ANBLO', 
'MHTIME', 'NBANSW']:
         if block is not None:
             blocks.append(block)
         block = []
     elif block is not None:
         res = pattern.match(line.strip())
         if res:
             values = list(res.groups())
             values[1:] = map(float,values[1:])
             block.append(values)
if block is not None:
     blocks.append(block)

for idx,block in enumerate(blocks):
     print "BLOCK",idx
     for values in block:
         print values

This prints:

BLOCK 0
['AABBCCO', 6.4, 204.0, 0.0, 115.0, 1.0, 113.4, 144.0]
['DDEEFFO', 0.2, 5.0, 0.0, 59.0, 0.0, 107.6, 3.0]
['HHGGFFO', 0.0, 0.0, 0.0, 30.0, 0.0, 0.0, 0.0]




More information about the Python-list mailing list