can python do this?

Ray Loyzaga ray at commsecure.com.au
Tue Jun 13 06:45:48 EDT 2000


Courageous wrote:
> 
> Q: "Can python do this?"
> A: "Python was born for it, baybee!"
> 
> import string
> file = open ("file")
> lines = file.readlines()
> for line in lines:
>     pair = string.split(line,":")
>     print pair[0] +": "+ `string.split(string.strip(pair[1]),",")`
> file.close()

I think his specification was a little more complex, he wanted to choose a
subset of
lines (those that he indicated by the use of the ** prefix). In addition the
"CMLISTPTRACKS"
field can span multiple lines, since it is a list of the tracks on the album.
And I also believe that he is expecting many of these per file, i.e. that the
input file has a list of the information associated with all of the new albums
that have been added to the catalogue.

The following might do what he wants, it uses the CMTYPE label to
indicate the end of the current run of album info.
Edit TITLE to suit your needs for the first line title.
It reads data from stdin, and writes to stdout.

#!/usr/local/bin/python
import sys, string

TITLE = 'Title\tArtist\tCat no\tAPN\tPrice Code\tMedia Code\tDist
Code\tRelease\tTracks\tPrice\tType'
keep_list = ['CPTITLE', 'CPARTIST', 'CMCATNUMBER' 'CMCATNUMBER', 'CMAPN',
                'CMARIAPRICECODE', 'CMARIAMEDIACODE', 'CMARIADISTRIBUTORCODE',
                'DMRELEASE', 'CMLISTPTRACKS', 'CURMPRICE', 'CMTYPE']
LAST_ATTRIBUTE = 'CMTYPE'

print TITLE
row_strs = []
tracks = []
in_track = 0
for line in sys.stdin.readlines():
        fields = string.split(line[:-1], ':')
        if in_track or fields[0] in keep_list:
                if len(fields) == 2:
			# multi-line record, store in tracks
                        if fields[0] == 'CMLISTPTRACKS':
                                tracks.append(fields[1])
                                in_track = 1
                        else:
                                if in_track:
                                        in_track = 0
                                        row_strs.append(string.join(tracks, '
'))
                                else:
                                        row_strs.append(string.strip(fields[1]))
                else:
                        if in_track:
                                tracks.append(line[:-1])
		# end of record, print result
                if fields[0] == LAST_ATTRIBUTE:
                        print string.join(row_strs, '\t')
                        row_strs = []
                        tracks = []



More information about the Python-list mailing list